我正在尝试修改我的程序,以便即使用户输入了字符串而不是程序崩溃,它也应该继续循环并要求用户输入需要为整数的考试成绩,只有当用户输入了整数时程序才会终止。我指的是 do-while block 中的代码
import java.util.InputMismatchException;
import java.util.Scanner;
public class CatchingException {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int score;
String choice;
try {
System.out.println("Enter your percentage mark: ");
score = scan.nextInt();
do {
if(score <40) {
System.out.println("You FAILED");
}else if(score >=40 && score <50){
System.out.println("Your grade: PASS MARK");
}else if(score >=50 && score <60) {
System.out.println("Your grade: 2:2");
}else if (score >=60 && score <70) {
System.out.println("Your grade: 2:1");
}else {
System.out.println("Your grade: 1:1");
}
System.out.println("Do you want to enter another grade: ");
choice = scan.next();
if(choice.equalsIgnoreCase("yes")) {
System.out.println("Enter your percentage mark: ");
score = scan.nextInt();
System.err.println("Incorrect Input");
}
}while();
}catch(InputMismatchException e) {
System.err.println("Incorrect Input ");
}
System.out.println("program terminated");
scan.close();
}
}
最佳答案
使用 boolean 变量来跟踪是否继续循环。例如:
boolean loop = true;
do {
// set loop to false when you want to end
} while(loop);
关于java - 如何让程序一直循环直到用户输入一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28254474/