簡體   English   中英

我在Java作業中遇到猜謎游戲時遇到問題

[英]Having some trouble with a guessing game I have for an assignment in Java

這只是我的Comp Stro入門課程的一小部分作業,但是我遇到了一些麻煩,我必須提示用戶驗證代碼是否正確,然后如果出現錯誤,它將提示是否更高或更低等等。 我想這樣做,如果最大數字范圍是12,我將從6開始,然后我首先要問用戶:是否正確? 如果不是,則詢問它是更高還是更低。 根據他的回答,我的下一個值將在0到6之間,即3,或者6到12之間,即9。 如果您可以幫助我解決我的代碼,或者可以指導我獲得一個不錯的答案!

Scanner in = new Scanner(System.in);
boolean guess = false;

int maxMonth = 12;
int minMonth = 0;
int month = (maxMonth - minMonth) / 2;
int total = 6;

while (guess == false) {
    String yes = "yes";
    String no = "no";
    int tries = 0;
    boolean firstGuess = false;

    System.out.println("Is your birthday in " + month + " yes or no:");
    String a1 = in.next();

    if (a1.equals(yes)) {
        firstGuess = true;
    } else {
        System.out.println("Is your birthday after this month?");
        String a2 = in.next();

        if (a2.equals(yes)) {
            total++;
            total = (int) total / 2;
            month = month + total;
        } else {
            total = total - 3;
            total = (int) total / 2;
            month = month + total;
        }
    }

    //guesses the day in the month
    while (firstGuess == true) { }
}

您需要在循環內計算month的值。 每次猜測之后,如果a2是,則更新minMonth = month + 1,如果a2如果沒有,則更新maxMonth = month-1,然后再次循環(重新計算month =(maxMonth-minMonth)/ 2)。

同樣,循環的條件是while(guess == false),但是您永遠不會更改guess的值,因此您永遠都無法退出循環。 您需要if(a1.equals(yes))guess = true; (不是firstGuess)。

暫無
暫無

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

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