[英]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.