2013-07-03 22 views
1

我有一個小麻煩抓的區別! ||當他們在一段時間的條件下進行測試時,它們將被編號爲& &。在下面的例子中,我希望程序提出一個問題:「你看到屏幕上有四個?」那麼如果這個人沒有答案,那麼這個計劃會繼續下去,並繼續問。如果用戶輸入答案「是」,則程序退出但我的程序不存在。

在我while循環的條件我要告訴while循環繼續只要我都小於5,問題的答案是肯定的不是?如何正確的思考方式! ||和& &在while循環的上下文中使用?測試真/假的條件使用! ||和&&運營商

import acm.program.*; 

public class WhileConditionTestProgram extends ConsoleProgram{ 
public void run(){ 

String question = ("do you see a four on the screen? "); 
int i = 1; 

    while(i <= 20 && !(question.equals("yes"))){ 
    String question = readLine("do you see a 4 on the screen?: "); 
    i++; 
    } 

    } 
    } 
+2

請仔細觀察while循環內的變量名稱以及您在條件中使用的變量名稱。 –

+1

你永遠不會更新'答案',所以它永遠不會等於'「是」'。 – rgettman

+0

'字符串問題=的readLine(「你看到一個4在屏幕上?:」);' –

回答

0

這些運營商在while循環的工作方式相同,因爲他們工作在其他地方。

的& &和||運算符對兩個布爾表達式執行條件與和操作。

試試這個:

String answer = ""; 
int i = 1; 

    while(i <= 20 && !(answer.equalsIgnoreCase("yes"))){ 
    answer = readLine("do you see a 4 on the screen?: "); 
    i++; 
    } 
+0

您需要刪除重新聲明「String回答「在while循環中。你用一個新的答案變量來隱藏答案變量。 –

+0

@CoryKendall好的。 – Zzz

3

在你的while條件要測試的回答沒有質疑嘗試:

while(i <= 20 && !(answer.equals("yes"))){ 
answer = readLine("do you see a 4 on the screen?: "); 
i++; 
} 
+0

只要確保你首先聲明'answer'(指OP的當前代碼) – 2rs2ts

+0

fwiw代替使用'answer.equalsIgnoreCase()'可能是更好的做法 - 但這僅僅是爲了興趣 –

4

除了變量重新聲明的明顯的問題,你也應該考慮使用do-while循環,因爲你是至少閱讀一次用戶輸入。

所以,你可以更好地改變你的循環中:

int i = 0; 
String answer = ""; 

do { 
    answer = readLine("do you see a 4 on the screen?: "); 
    i++; 
} while (i <= 20 && !answer.equalsIgnoreCase("yes")); 

注:我已經使用equalsIgnoreCase只是爲了安全方面,因爲你是從用戶讀取輸入。你永遠不知道它傳遞的是什麼字母組合。

1

這段代碼的問題:

String question = ("do you see a four on the screen? "); 
int i = 1; 

while(i <= 20 && !(question.equals("yes"))){ 
    String question = readLine("do you see a 4 on the screen?: "); 
    i++; 
} 

這就是你重新定義,而函數內部的question變量。作爲一個例子,這將打印「1」,而不是「2」:

String question = "1"; 
int i = 1; 

while (i <= 20) { 
    String question = "2"; 
    i++; 
} 

System.out.println("Question is: " + question); // This will print "1"! 

當你說String question = "2"您聲明稱爲question一個全新的變量,將其設置爲「2」。當您到達while循環的末尾時,該變量超出範圍,程序將丟棄其數據。原始question未觸及。以下是該代碼段的更正版本:

String question = ("do you see a four on the screen?"); 
int i = 1; 

while(i <= 20 && !(question.equals("yes"))){ 
    question = readLine("do you see a 4 on the screen?: "); 
    i++; 
}