-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 回答