我试图让用户有 3 次机会输入正确的输入,第三次尝试后程序应该关闭,我将给出一个自定义字符串。如果他们在任何时候输入有效数据,程序就应该执行。我想在代码中添加错误处理:
import java.util.Scanner;
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int month, day; String season = null;
System.out.print("Enter Month & Day: ");
month = in.nextInt(); day = in.nextInt();
if(1 <= month && month <= 3){
season = "Winter";
if((month == 3) && (21 <= day))
season = "Spring";
} else if (4 <= month && month <=6){
season = "Spring";
if((month == 6) && (21 <= day))
season = "Summer";
} else if (7 <=month && month <=9){
season = "Summer";
if((month == 9) && (21 <= day))
season = "Fall";
} else if (10 <= month && month <= 12){
season = "Fall";
if((month == 12) && (21 <= day))
season = "Winter";
}
System.out.println(season);
}
}
最佳答案
这样的事情可能会对您有所帮助。代码是不言自明的。
private static final int RETRY_COUNT = 3
retryCount = 0
boolean invalid = true;
while(invalid && retryCount++ < RETRY_COUNT){
try{
invalid = false;
Scanner sc = new Scanner(System.in)
.
.
.
}catch(Exception e){
invalid = true;
}
}
关于java - 如何向我的代码添加错误处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46880866/