簡體   English   中英

Java Do While Statement有兩個條件

[英]Java Do While Statement with two conditions

我正在嘗試學習java,但我一直試圖做一個關於Do While Statement的單個程序,有兩個條件。 具體來說,我想要一個方法運行,直到用戶寫“是”或“否”。 那么,有我的東西,它有什么問題?

    String answerString;
    Scanner user_input = new Scanner(System.in);
    System.out.println("Do you want a cookie? ");

    do{
    answerString = user_input.next();
    if(answerString.equalsIgnoreCase("yes")){
        System.out.println("You want a cookie.");
    }else if(answerString.equalsIgnoreCase("no")){
        System.out.println("You don't want a cookie.");
    }else{
        System.out.println("Answer by saying 'yes' or 'no'");
    }while(user_input == 'yes' || user_input == 'no');
    }
}}

我會做一些類似蒂姆的回答。 但是,按照你試圖做的方式做事,你有很多需要修復的問題:

(1)Java中的字符串文字由雙引號括起,而不是單引號。

(2) user_input是一個Scanner 您無法將掃描儀與字符串進行比較。 您只能將String與另一個String進行比較。 所以你應該在比較中使用answerString ,而不是user_input

(3)永遠不要使用==來比較字符串。 StackOverflow有953,235個Java問題,其中大約826,102個涉及有人試圖使用==來比較字符串。 (好吧,這有點誇張。)使用equals方法: string1.equals(string2)

(4)編寫do-while循環時,語法為do ,后跟{ ,后跟循環中的代碼,后跟} ,然后是while(condition); 它看起來像你把最后}在錯誤的地方。 }在之前while屬於else ,這樣不計; 你需要另一個}之前, while不是之后。

(5)我覺得你試圖寫一個循環,不斷去,如果輸入的是不yesno 相反,你卻反其道而行之:你寫了一個循環,只要輸入不斷去yesno while條件應該是這個樣子

while (!(answerString.equals("yes") || answerString.equals("no")));

[實際上,應該將equalsIgnoreCase與其余代碼保持一致。] ! 在這里意味着“不”,並注意到我必須把整個表達式放在括號之后! ,否則! 只會應用於表達式的第一部分。 如果你正在嘗試編寫一個“循環直到等等等”的循環,你必須把它寫成“Loop while ! (blah-blah-blah)”。

我可能會選擇一個do循環,它將繼續接受命令行用戶輸入,直到他輸入“是”或“否”答案,此時循環中斷。

do {
    answerString = user_input.next();

    if ("yes".equalsIgnoreCase(answerString)) {
        System.out.println("You want a cookie.");
        break;
    } else if ("no".equalsIgnoreCase(answerString)) {
        System.out.println("You don't want a cookie.");
        break;
    } else {
        System.out.println("Answer by saying 'yes' or 'no'");
    }
} while(true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM