2014-09-19 50 views
1

我在WHILE語句中嵌套了一個IF ELSE語句,但是對於爲什麼在ELSE之前解釋WHILE(當IF失敗時)感到困惑。要求用戶輸入1-10(包含)的數字。如果該數字在該範圍內,則程序結束。如果超出範圍,我想顯示一個錯誤,然後提示他們再次輸入一個數字。WHILE在評估ELSE之前重複

如果我在WHILE之前加上「提示符」,它會很好地工作,但是我必須再次將其放入ELSE語句中,以便它再次出現。我發現這question,但它似乎沒有回答我遇到的問題。我承認是Java新手,所以我很抱歉如果我錯過了Java的一些基本方面。

import java.util.Scanner; 
public class Rangecheck { 
private static int userNumber; //Number input by user 
private static boolean numberOK = false; //Final check if number is valid 
//String that will be reused in the DO statement 
private static String enterNumber = "Please enter a number from 1 to 10: "; 

public static void main(String[] args) { 
//Print string 
while(!numberOK) // Repeat until the number is OK 
{ System.out.println(enterNumber); 
Scanner input_UserNumber = new Scanner(System.in); //input integer 
userNumber = input_UserNumber.nextInt(); 

if (10>= userNumber && userNumber >= 1) //Check if 10>=input>=1 
{ 
    /* 
    ** If number was valid, congratulate the user and mark numberOK true 
    */ 
    System.out.println("Good job! The number you entered is "+userNumber+"."); 
     numberOK = true; // Congratulate user/exit loop if successful 
} 
else ; //if (10 < userNumber && userNumber < 1) 
{ 
     System.err.println("The number entered was not between 1 and 10!"); 
     System.err.print(enterNumber); // Error; user retries until successful 
      } 

} 

} 
} 

我期望的System.err.println()else聲明進行評估,然後while進行評估,因此,這得到返回:

The number entered was not between 1 and 10!  
    Please enter a number between 1 and 10: 

我有點繞這個工作由在while之前放入enterNumber,然後在錯誤後立即在else語句中放第二個 println。它回報了我的期望,但我相信我從根本上誤解了一些東西。

+0

嘛別的評價?你還怎麼解釋說'輸入的數字不在1到10之間!「'是否打印? – 2014-09-19 01:18:10

+0

嘗試在應用程序的開始部分放置一個斷點,然後逐行遍歷每一行以幫助您理解執行順序 – StriplingWarrior 2014-09-19 01:20:43

+0

使用掃描程序時看起來像是一個問題請提供您的完整代碼應用程序來檢查錯誤的位置 – 2014-09-19 01:25:00

回答

0

else聲明在while聲明之前重複。但有時可能會出現Stream s的問題。 A Stream不一定立即打印數據。特別是在使用兩個不同流的情況下,打印輸出數據的順序可以交錯。

您可以使用:

System.err.flush(); 

,以確保數據寫入到控制檯第一。

+0

實際上,最好不要將簡單的文本消息打印到stderr,而只需使用stdout。 – nmore 2014-09-19 01:31:02

+0

@nmore:Linux中的標準是 - 據我所知 - 處理'stderr上的所有用戶交互','stdout'只用於「打印某些語義」,例如,如果一個人運行交互式shell,''>'等應該打印在'sterr'。 – 2014-09-19 02:31:16

+0

謝謝@CommuSoft。 'err.println()'似乎有幫助,但顯示錯誤,不管數字是否符合範圍。我發現如果我使用'System.out.println()'而不是'System.err.pr intln()',即使沒有刷新,它也能正常工作。 我不知道'Stream'如何發揮作用。 – Bill 2014-09-21 00:07:06

0

讓我們假設你有下面的代碼:

while (whileCondition) { 
    //Inside while, before if 
    if (ifCondition) { 
     //Inside if 
    } else { 
     //Inside else 
    } 
} 

這個循環將重複執行,直到whileCondition變得false。每當ifConditiontrue時,將執行if內部的操作,否則將執行else內部的操作。

回到你的問題:

你的

System.out.println(enterNumber); 

線處於while的開始。因此,在代碼甚至到達if之前,控制檯上將顯示enterNumber的內容。之後,對if進行評估,如果輸入,比如說22,則給予if的條件將爲false,並且將評估else塊的內容。

+0

如果我明白,這個答案指出代碼應該按預期工作。再一次,就像我在我的評論中發佈的那樣,這似乎是使用'Scanner'時的錯誤,可能是由於閱讀時不使用nextLine或類似的東西,但我們不能確定,因爲OP不會發布更多的代碼。 – 2014-09-19 01:34:10

0

在別人身上添加以下語句:

numberOk=false;