gpt4 book ai didi

java - 程序错误地打印到控制台

转载 作者:行者123 更新时间:2023-12-02 05:01:28 25 4
gpt4 key购买 nike

我创建了一个程序,要求用户输入(成绩)。我使用 try/catch 语句来捕获 InputMismatchException,以防用户输入不正确的数据类型。问题发生在第二个 try/catch 语句期间。当程序询问“输入你的百分比分数?”后在 if 语句中,用户输入了错误的数据类型。然后,程序会重新打印您的成绩两次,并询问您是否要输入两次成绩。

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")) {
try{
System.out.println("Enter your percentage mark: ");
score = scan.nextInt();
}catch(InputMismatchException e) {
System.err.print("Incorrect Input");
}
}
}while(!choice.equalsIgnoreCase("No"));

}catch(InputMismatchException e) {
System.err.println("Incorrect Input ");
}

System.out.println("program terminated");
scan.close();

}

}

最佳答案

您的 catch block 不会转移控制权。 (例如,通过返回或抛出另一个异常)这意味着在打印消息后,程序检查 while 条件。由于在这种情况下该条件永远不会成立,因此它将使用分数重新运行循环。

本来会更新分数的语句引发了异常,因此未更新。

关于java - 程序错误地打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28253597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com