简体   繁体   中英

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

My program doesn't output anything to the console. I'm not sure what I did wrong. I'm required to use System.in.read() and can't use a Scanner . I'm also required to use any loop of my choice.

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."); 
            }
        } 
    }
}

This line:

while(correct == false);

needs to lose the semicolon at the end. As it stands now, it's an infinite empty loop and your program won't proceed past that statement.

To add to Greg's answer, System.in.read() returns a char . If you store it in an int you will have the ASCII representation of the value.

For example 56 is the ASCII for '8'. The offset of the numbers in the ASCII table in HEX is 0x30. So, for the code to actually work, you should subtract 0x30 to the received value.

So, you should change the input line to the following one:

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

First, when you have a boolean type, there is no need for you to check (correct == false) , you can simply use the operator ! like this (!correct)

The problem that you have is that you are using the semicolon after the while, while loop has no semicolon. So you have this while(!correct); , so it stays on an infinite loop without executing the inner block of code

    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."); 
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM