簡體   English   中英

為什么我的猜數字游戲沒有向控制台輸出任何信息?

[英]Why doesn't my number guessing game output anything to the console?

我的程序沒有任何輸出到控制台。 我不確定自己做錯了什么。 我需要使用System.in.read()而不能使用Scanner 我還需要使用我選擇的任何循環。

package MyGuessingGame;
import java.io.IOException;

/**
*
* @author Anthony
*/
public class MyGuessingGame {

    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String[] args) throws IOException {

        int guess = 0;
        int answer = 8;
        //Todo change to random
        boolean correct = false;

        while (correct == false); {
            System.out.println("Please enter your guess!");
            guess = System.in.read();
            System.in.read();
            if (guess == answer) {
                correct = true;
                System.out.println("Congradulations You have won!"); 
            } else if (guess != answer) {
                correct = false;
                System.out.println("Sorry try again."); 
            }
        } 
    }
}

這行:

while(correct == false);

最后需要輸掉分號。 就目前而言,這是一個無限的空循環,您的程序不會繼續執行該語句。

為了增加Greg的答案, System.in.read()返回一個char 如果將其存儲在int ,則將具有該值的ASCII表示形式。

例如56是ASCII的'8'。 HEX的ASCII表中數字的偏移量為0x30。 因此,為使代碼真正起作用,應將接收值減去0x30。

因此,您應該將輸入行更改為以下一行:

guess = System.in.read() - 0x30;

首先,當您具有boolean類型時,不需要檢查(correct == false) ,您可以簡單地使用運算符! 像這樣(!correct)

您遇到的問題是,在while,while循環后沒有分號的情況下使用了分號。 所以你有這個while(!correct); ,因此它不執行內部代碼塊就處於無限循環

    int guess = 0;
    int answer = 8;
    //Todo change to random
    boolean correct = false;

    while(!correct)
    {
        System.out.println("Please enter your guess!");
        guess = System.in.read();
        if (guess == answer) {
            correct = true;
            System.out.println("Congradulations You have won!");
        }  else {
            System.out.println("Sorry try again."); 
        }
    }

暫無
暫無

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

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