-3
public static void main(String[] args) {
    // TODO code application logic here
    Scanner input = new Scanner(System.in);
    do{
        System.out.print("Enter choice:");
        int choice;
        choice = input.nextInt();
        switch (choice) 
        {
            case 1: 
                FirstProject.areaRectangle();
                break;
            case 2:
                FirstProject.areaTriangle();
                break;
            default:
                System.out.println("lol");
                break;
        }
    }while (input.nextInt()!=0);    
}




public static void areaRectangle() {
    Scanner input = new Scanner(System.in);
    System.out.println("Area of a rectangle.");

    System.out.print("Enter the width: ");
    double width;
    width = input.nextInt();

    System.out.print("Enter the height: ");
    double height;
    height = input.nextInt();

    double areaRectangle = (width * height);

    System.out.println("The Area of the rectangle is: " + areaRectangle);


    }
public static void areaTriangle() {
    Scanner input = new Scanner(System.in);
    System.out.println("Area of a triangle.");

    System.out.print("Enter the base: ");
    double base;
    base = input.nextInt();

    System.out.print("Enter the height: ");
    double height;
    height = input.nextInt();

    double areaTriangle = (base * height) / 2;

    System.out.println("The Area of the triangle is: " + areaTriangle);
}
}

それが私のコードであり、機能します。私を悩ませている唯一のことは、ループを維持するために「0」を除く任意の値を入力する必要があることです。たとえば、ケース 1 を選択した場合、メソッドは実行されますが、実行後、ループを続行するには値を入力する必要があります。何か案は?

4

1 に答える 1

7

これが問題です:

while (input.nextInt()!=0);

それは別の数字を要求しますが、それを覚えていません.0かどうかをチェックするだけです.

次のようなものが必要だと思います:

while (true) {
  System.out.print("Enter choice:");
  int choice = input.nextInt();
  if (choice == 0) {
    break;
  }
  switch (choice) {
    // Code as before
  }
}

少し醜い「手動で壊れるまで無限」ループを必要としないこのコードを書く方法がありますが、他の方法では少し奇妙です。例えば:

int choice;
do {
  System.out.print("Enter choice:");
  choice = input.nextInt();
  switch (choice) {
    // Code as before... except work out whether you want to print anything on 0
  }
} while (choice != 0);

いずれにせよ、0 が入力されたときに何をしたいのかを本当に検討する必要があります。すぐに中断するか、「lol」を出力してから中断しますか? あなたはいつでも持つことができます:

case 0:
    break;

switch ステートメントで 0 に対して何も出力しないようにする場合。

于 2013-10-24T16:50:09.927 に答える