![](/img/trans.png)
[英]Why does a Java Compiler not produce an unreachable statement error for an unreachable then statement?
[英]Why does the statement after the comment Digit 2 is getting marked as “unreachable”?
在下面的代码中,数字2之后的语句标记为不可访问。 为什么?
while(true){
System.out.println("Welcome to Pi Conquest!");
System.out.println("Name as many digits of Pi as you can");
System.out.println("If you get an error you restart");
System.out.println("Only includes up to 100 digits of Pi");
System.out.println("---------------------------------------");
System.out.println("");
Scanner keyboard = new Scanner(System.in);
//Digit 1
System.out.println("Stats:");
System.out.println("Number of Digits Entered: 0");
System.out.println("Digits Entered: 3.");
System.out.println("Enter the first digit of Pi. (Starting with decimals)");
int digit1 = keyboard.nextInt();
if(digit1==1){
System.out.println("Correct, enter the next digit.");
continue;
}else{
System.out.println("Incorrect, restarting.");
break;
}
//Digit 2 <--------------------------------------- next statement marked unreachable
System.out.println("Stats:");
System.out.println("Number of Digits Entered: 1");
System.out.println("Digits Entered: 3.1");
int digit2 = keyboard.nextInt();
if(digit2==4){
System.out.println("Correct, enter the next digit.");
continue;
}else{
System.out.println("Incorrect, restarting.");
break;
}
}
因为在上一个if
,将执行以continue
结尾的分支或以break
结尾的分支。
这两条指令都将导致当前迭代结束,因此无法执行更多代码。
该语句中的第一个选项导致重新启动循环,第二个选项-结束循环并在while循环之后开始执行代码。 因此,将不会到达下一行。
if(digit1==1){
System.out.println("Correct, enter the next digit.");
continue;
}else{
System.out.println("Incorrect, restarting.");
break;
}
您正在使用continue
并break
错误。 您的break
应该是“ continue
而您的“ continue
应该被简单地删除。
if(digit1==1){
System.out.println("Correct, enter the next digit.");
}else{
System.out.println("Incorrect, restarting.");
continue;
}
break
退出while(true)
循环,由于该循环之后没有其他内容,因此程序结束。 相反,您想在此时开始一个新的循环迭代(并跳过当前迭代的其余部分),因此您需要continue
。
如前所述, continue
开始新的循环迭代。 相反,您只想继续当前的迭代即可。 您不需要花哨的东西:只需让if
块执行其操作并在if...else
语句之后继续。
题外话:如果以此方式继续输入其他数字,您将有很多代码重复。 我建议您考虑对pi的数字进行 for
循环,以便可以将“当前数字”与输入的数字进行比较。
您的第一个if语句失败或继续循环(它不会继续执行“代码”),因此第一个if语句之后将不会执行任何操作。
您可能需要考虑对请求进行不同的编码(例如,在字符串答案中逐步浏览pi的数字,从而向用户提供反馈)。
//Digit 2
注释下的所有代码均无法访问。 我认为您没有得到continue
声明的意思。 当您运行while
循环时,它会从键盘获取int
int digit1 = keyboard.nextInt();
并根据您的代码
if(digit1==1){
System.out.println("Correct, enter the next digit.");
continue;
}else{
System.out.println("Incorrect, restarting.");
break;
}
如果为1
,则将从头开始循环。 否则循环将中断。 我认为您希望在if else
语句之后continue
运行您的代码,但是continue
run从一开始就再次循环。
如果要在之后运行下一行代码, if else
删除继续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.