1

シリンダーの体積を見つけるためにwhileを使用するプログラムを作成する必要があります。ユーザーが高さに負の値を入力した場合、whileループを中断する必要があります。私のコードは次のようになります:

double sentinel=1, h=1, v=0, r, count=0; // declares all variables needed
    final double PI=3.14159;
    boolean NotNegative=true;

while(NotNegative){// && count==0){ // while both the height is positive AND the total times run is 0
        System.out.print("Enter height (Use negative to exit): "); // has the user input the height
        h=Double.parseDouble(br.readLine());
        sentinel=h; // save sentinel as the inputted height

        while(sentinel>0){

           System.out.print("Enter radius: "); // have the user input the radius
           r=Double.parseDouble(br.readLine());
           v=PI*(r*r)*h; // find the volume
           System.out.println("The volume is " + v); // print out the volume
           count++; // increase the count each time this runs
           NotNegative=true;
           sentinel=-1;
        }
    }   

何か助けはありますか?

4

2 に答える 2

2

キャッチして無視する例外をスローできます。これは悪い考えです

  • if および/または break はより効率的でシンプルです。
  • 遅いです
  • ややこしい。

ただし、if & break を使用するような while ループを使用しているため、次のことができます。

NotNegative = h >= 0;
于 2012-12-03T17:01:52.207 に答える
0

while(NotNegative){入力を読み取った後、内に次のコードを追加します。

NotNegative = h >= 0;
于 2012-12-03T17:10:38.660 に答える