如果输入字符串值或与大小写无关的数字,如何不获取错误。
switch(optionIssues) {
case 1 : healthIssues = "Dental Problem"; ;break;
case 2 : healthIssues = "Respiratory Diphtheria";;break;
case 3 : healthIssues = "Mosquitoes Infections";;break;
} 发布于 2017-11-13 09:52:36
如果输入字符串,则可以通过将选项作为字符串读取或捕获异常来防止错误,如下所示:
int optionIssues;
try {
optionIssues = new Scanner(System.in).nextInt();
}
catch (Exception e) {
optionIssues = 0;
}无论如何,您的开关中应该有一个默认的情况:
switch(optionIssues){
case 1 : healthIssues = "Dental Problem"; break;
case 2 : healthIssues = "Respiratory Diphtheria"; break;
case 3 : healthIssues = "Mosquitoes Infections"; break;
default: System.out.println("Invalid option.");
}发布于 2017-11-13 09:47:35
您应该添加这样的默认情况:
switch(optionIssues){
case 1 : healthIssues = "Dental Problem";break;
case 2 : healthIssues = "Respiratory Diphtheria";break;
case 3 : healthIssues = "Mosquitoes Infections";break;
default : break;
}您可以看到更多关于它的信息,这里
发布于 2017-11-13 09:49:57
添加默认情况时,您将指示程序在所有情况都不满足时应该做什么。
switch(optionIssues){
case 1 : healthIssues = "Dental Problem"; ;break;
case 2 : healthIssues = "Respiratory Diphtheria";;break;
case 3 : healthIssues = "Mosquitoes Infections";;break;
default:
System.out.println("Introduce an integer between 1 and 3");
break;
}如果您想在用户没有引入正确的选项时返回到交换机,您可以使用一个with循环,其结束条件如下:
boolean exit = false;
System.out.println("Introduce number 4 to finish");
while(!exit) {
switch(optionIssues){
case 1 :
healthIssues = "Dental Problem";
break;
case 2 :
healthIssues = "Respiratory Diphtheria";
break;
case 3 :
healthIssues = "Mosquitoes Infections";
break;
case 4 :
exit = true;
break;
default:
System.out.println("Introduce an integer between 1 and 4, please");
break;
}
}这样,除非用户引入选项4,否则swith将被重复。如果您只想在引入了不正确的数字时重复它:
boolean repeat= true;
while(repeat) {
switch(optionIssues){
case 1 :
healthIssues = "Dental Problem";
repeat = false;
break;
case 2 :
healthIssues = "Respiratory Diphtheria";
repeat = false;
break;
case 3 :
healthIssues = "Mosquitoes Infections";
repeat = false;
break;
default:
System.out.println("Introduce an integer between 1 and 4, please");
break;
}
}如果用户引入一个5,则布尔重复是真的,所以它会重复。但是如果一个正确的数字,重复是假的,所以它会熄灭。
https://stackoverflow.com/questions/47261242
复制相似问题