2011-10-28 9 views
-3
import java.util.Scanner; 

public class Power1Eng { 

public static void main(String[] args) { 

    double x, prod = 1; 
    int n; 
    String s; 

    Scanner input = new Scanner(System.in); 

    System.out.print("This program prints x(x is a real number) raised to the power of n(n is an integer).\n"); 

    outer_loop: 
    while (true) { 
     System.out.print("Input x and n: "); 
     x = input.nextDouble(); 
     n = input.nextInt(); 

     for (int i = 1; i <= n; i++) { 
      prod *= x; 
     } 

     System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod); 
     s = input.nextLine(); 

     if (s.charAt(0) == 'Y') 
      continue; 
     else if (s.charAt(0) == 'N') 
      break; 
     else { 
      inner_loop: 
      while (true) { 
       System.out.print("Wrong input. Do you want to continue?(Y/N) "); 
       s = input.nextLine(); 

       if (s.charAt(0) == 'Y') 
        continue outer_loop; 
       else if (s.charAt(0) == 'N') 
        break outer_loop; 
       else 
        continue inner_loop; 
      } 
     } 
    }  
} 

} 

enter image description here「スレッドの例外」とより

あり、私はちょうどnext()メソッドを使用する場合のみ、些細な論理エラーでしたが、私はnextLine()方法、このエラーショーに next()方法を変更したとき。

この問題を解決するにはどうすればよいですか?

答えて

3

2つの問題があります。最初の文字列は空である可能性があり、最初の文字を取得すると例外が発生します。

if (s.charAt(0) == 'Y') // This will throw if is empty. 

どちらか少なくとも一つの文字があるかどうかを確認するために、文字列の長さをテストし、あるいは単にString.startsWithの代わりcharAtを使用します。

if (s.startsWith('Y')) 

第二の問題は、あなたが後に新しい行を入力したことですあなたの最初の入力、nextLineは次の改行文字だけを読み込みます。

0

最初の文字カウントを確認して、正しい文字数があることを確認できます。すなわち:

while (true) 
{ 
    // ... some code ... 

    if (s.length() < 1) 
    { 
     continue; 
    } 

    // ... some code ... 
} 

この方法で、あなたも、コードベースが大きかった場合、パフォーマンスを最適化するのに役立つだろうコードの残りの部分を実行し続けなければならないでしょう。

0

コンソールに表示される「赤いテキスト」は、テキストが標準エラーに送信されていることを示しています。この場合、プログラムがクラッシュしたことを示します。

あなたが直面している主な問題は、このロジックを使用することです:

System.out.print("Input x and n: "); 
x = input.nextDouble(); 
n = input.nextInt(); 

for (int i = 1; i <= n; i++) { 
    prod *= x; 
} 

System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod); 
s = input.nextLine(); 

は、ユーザーの入力があると仮定します。

input.nextDouble()(入力)

2.1 4、2.1がかかります4(enter)を標準入力ストリームに置きます。
input.nextInt()4となり、標準入力ストリームには(enter)が残っています。
input.nextLine()""(空の文字列)をとり、最初にxnの初期ユーザー入力から(enter)をクリアします。

関連する問題