Zaid A Zaid A - 1 month ago 10
Java Question

The Command Prompt just hangs after executing my java program

It seems like there is no problem with this code (here it is):

import java.util.*;

public class NumberGuessingGame {

static int randomNumber = (int) (Math.random() * 11);

static Scanner userInput = new Scanner(System.in);

static int guessedNumber = userInput.nextInt();

public static void main(String[] args) {

start: {

while (guessedNumber != randomNumber) {

System.out.println("I'm thinking of a number in my mind between 0 and 10. ");

delay(1500);

System.out.print("Try to guess it: ");

if (guessedNumber == randomNumber) {

System.out.print("Congradulations! ");

delay(800);

System.out.println("The number really was " + randomNumber);

} else {

break start;

}
}
}


}

public static void delay(int millis) {

try {

Thread.sleep(millis);

} catch (InterruptedException exp) {
}

}
}


If you couldn't tell already I'm a beginner trying to create a basic number guessing game. So I successfully coded it but now every time I execute it this happens:

prompt

It just freezes. Why?

Answer

The error is because your program is waiting for an user input. According to the docs, a Scanning operation may block waiting for input

The solution is implementing a do/while and userInput and guessedNumber initialized when they are required.

NumberGuessingGame:

import java.util.*;

public class NumberGuessingGame {

static int randomNumber = (int) (Math.random() * 11);

static Scanner userInput;

static int guessedNumber;


public static void main(String[] args) {

        System.out.println("I'm thinking of a number in my mind between 0 and 10. ");

        do
        {


            delay(1500);

            System.out.print("Try to guess it: ");
            userInput = new Scanner(System.in);
            guessedNumber = userInput.nextInt();

            if (guessedNumber == randomNumber) {

                System.out.print("Congratulations! ");

                delay(800);

                System.out.println("The number really was " + randomNumber);

            } else {

                System.out.println("Error, try again! ");

                delay(800);

            }
        }
        while (guessedNumber != randomNumber);

}

public static void delay(int millis) {

   try {

           Thread.sleep(millis);

       } catch (InterruptedException exp) {
   }

}   

}

Documentation:

do-while statement