2011-10-28 5 views
0
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.equals("Y")) 
       continue; 
      else if (s.equals("N")) 
       break; 
      else { 
       inner_loop: 
       while (true) { 
        System.out.print("Wrong input. Do you want to continue?(Y/N) "); 
        s = input.nextLine(); 

        if (s.equals("Y")) 
         continue outer_loop; 
        else if (s.equals("N")) 
         break outer_loop; 
        else 
         continue inner_loop; 
       } 
      } 
     }  
    } 

} 

enter image description hereプログラムは、予想される時点で(文字列を受け取るために)コンソールで

ルックを停止しないでください。 3行目では、最初の「続行しますか(Y/N)」までプログラムが印刷されると期待していましたが、「間違った入力」も表示されます。続行しますか?(Y/N) '。この問題を解決するにはどうすればよいですか?

+0

あなたのJavaは非常に非常に非常に悪いスタイルを持っています。タグやジャンプ先は使用しないでください。コードを読むことができなくなります。 コーディング規則を読む必要があります。http://www.oracle.com/technetwork/java/codeconv-138413.html – NCode

+0

「continue」と「break」をラベルに付けてください。このgotoに相当するgotoは絶対必要ではありません。 –

+0

NCode 1週間前にJavaを勉強し始めたので、コードが悪いと私は同意します! – schizoid322

答えて

1

nextIntnextDoubleを実行すると、(空の)残りの行はクリアされません。

これらの値を読み取り、残りの行をクリアした後にnextLineに電話する必要があります。

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

これは問題を解決し、ラベルも使用しません。

Should I avoid using Java Label Statements?

そのコードを維持するために取得する人々があなたを見つけるでしょう。

関連する問題