2017-02-22 186 views
-1

我正在處理一些代碼,它接受用戶輸入,並在輸入不是程序所要查找的內容時使用while語句循環。
由於某些原因,即使條件未滿足,while語句也始終執行。
我試過修復條件,但我不知道發生了什麼事。雖然循環跳過條件

do { 
    System.out.println("Enter a height within 0 and 23"); 
    height = s.nextInt(); 
} while (height < 0 || height > 23);{ 
    System.out.println("Please enter an integer within 0 and 23"); 
    height = s.nextInt(); 
} 

任何幫助,非常感謝!

+2

如果分號除去該代碼將是無效 - 'while'和前面的'do'循環一起,而不是跟在下面的塊。 –

+0

要添加到以前的評論,第二組花括號與此代碼段無關。 – SteveFerg

回答

0

我認爲一個標準while循環會適合你更好

int height = 0; 
while (True) { 
    System.out.println("Enter a height within 0 and 23"); 
    height = s.nextInt(); 
    if (height < 0 || height > 23) { 
     System.out.println("Please enter an integer within 0 and 23"); 
     continue; 
    } else break; 
} 

基本上,這個「碼塊」沒有應用到一個做而

{ 
    System.out.println("Please enter an integer within 0 and 23"); 
    height = s.nextInt(); 
} 
+0

啊,這可以幫助我與這個謝謝 –

+0

很高興聽到它。你可以通過[接受答案]來顯示你的感謝(// stackoverflow.com/help/someone-answers)。 –

1

你有while語句代碼太多。所有你需要的是:

do { 
    System.out.println("Enter a height within 0 and 23"); 
    height = s.nextInt(); 
} while (height < 0 || height > 23); 

一個do ... while循環有while底,而不是開始。

+0

我想你錯過了「請輸入」提示 –

+0

這個答案是正確的,但也許可以添加更多解釋爲什麼。 do while循環執行第一個{}對之間的代碼至少一次,如果條件爲真(在代碼塊執行後評估),則執行更多次。因此,時間之後的第二個代碼塊就在它自己的代碼塊中,與任何循環無關,因此是不必要的。 – Encaitar

0

你有一個do循環和一個while循環混合在一起。擺脫「do {」和第一個「}」。也請做什麼shmosel說,並刪除「;」。這將允許您在while循環外獲得第一個int,然後如果它在您的條件之內,它將開始循環。

System.out.println("Enter a height within 0 and 23"); 
    height = s.nextInt(); 
    // now have 1st condition for the whie loop 
    while (height < 0 || height > 23) { 
    System.out.println("Please enter an integer within 0 and 23"); 
    height = s.nextInt(); 
    } 
0

正如問題中所述,while語句總是在即使條件不滿足時執行。但這不是事實。

while循環是沒有得到執行用於輸入時的高度在0和23(含) 輸入之間:0 < =高度< = 23