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,它将执行该方法但在执行之后,我必须输入任何值以继续循环。有什么想法吗?
答案 0 :(得分: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。