我正在开始学习 Java 7 软件设计,学习 switch() 和 do...while () 等等。
当我在 Intelli J IDEA 13 中编译并运行该程序时,它编译并运行良好,但语句完成后不会出现任何中断。
例如,当程序运行时,在情况 2 中,当我输入 3 个成绩(90、90、90、-1)后输入 -1 时,它会给出平均值(270),但随后会重复。 .
它应该中断并返回到切换菜单的开头。即使当我在菜单中输入 3 时,它也只是显示“这里没有代码...”,直到无穷大,即使有一个break语句(即使break语句已经过时)。
import java.util.Scanner;
public class TestingPlatform {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter 1 to set percentage of total for new grades, 2 to enter new grades, 3 to get average, and 4 to quit: ");
int choice = input.nextInt();
do {
switch (choice) {
case 1:
System.out.println("Enter percent to multiply by: ");
double percent = input.nextDouble();
System.out.println("You entered " + percent);
break;
case 2:
int total;
int gradeCounter;
int grade;
double average;
total = 0;
gradeCounter = 0;
System.out.println("Enter grade or -1 to quit: ");
grade = input.nextInt();
while (grade != -1) {
total = total + grade;
gradeCounter = gradeCounter + 1;
System.out.println("Enter grade or -1 to quit: ");
grade = input.nextInt();
}
if (gradeCounter != 0) {
average = (double) total / gradeCounter;
System.out.printf("\nTotal of the %d grades is %d\n", gradeCounter, total);
System.out.printf("Class average is %.2f\n", average);
} else
System.out.println("No grades were entered.");
break;
case 3:
System.out.println("No code here yet....");
break;
}
} while (choice != 4);
}
}
最佳答案
您只接受一次输入,然后在输入不是 4 时循环。由于输入永远不会改变,所以永远不会改变。
开关内的break
只是跳出switch
。然后继续循环。
放置这些行:
System.out.println("Enter 1 to set percentage of total for new grades, 2 to enter new grades, 3 to get average, and 4 to quit: ");
choice = input.nextInt();
在 do
循环内部,而不是外部。然后每次循环时都会要求新的输入。
不过,您必须在循环外部声明 choice
,因为您在底部的 while
中引用了它。
将此行放在 do
循环上方:
int choice;
关于java - switch 语句不会中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21691007/