Home > Net >  Why can I not enter the while loop? (Java)
Why can I not enter the while loop? (Java)

Time:10-12

I can't seem to get into the while loop without including a System.out.print() at the top. I want to prompt the user to enter their value within the while loop.

import java.util.Scanner; import java.util.Random;

public class Lab1 {

public static void main(String[] args) {
    
    // create scanner 
    Scanner kbd = new Scanner(System.in);   
    
    // receive input values  
    int input = kbd.nextInt(); 
    
    // create random number generator 
    Random generator = new Random(); 
    int rNum = generator.nextInt(100) 1;
            
    // initialize counter 
    int counter = 0;
    
    
    while (input != rNum && counter < 10 )
    {
        //prompt user
        System.out.print("Enter your guess at my number ");
        input = kbd.nextInt(); 
        
        counter  ; 
        
        if (input < rNum) 
        {
            System.out.println("Guess is too small");
        }
        
        else if (input > rNum) 
        {
            System.out.println("Guess is too large");
        }
        
        if (input == rNum) 
        {
            System.out.println("You got it, in "   counter   " guesses!"); 
            
        }
        
        else if (counter == 10) 
         {
            if (input != rNum)
            {
                System.out.println("The correct answer is: "   rNum);
            }
        
         }
    

    }
        
    //close scanner 
    kbd.close();

}

}

CodePudding user response:

Whenever u use a statement which takes input - in your case - int input = kbd.nextInt(); , the java application stops executing right there and waits for a input from the specified source (System.in here) , try executing the code again , and this time input a random number which will be the value of input variable after that the loop will start. Also, in this case of the game u should change int input = kbd.nextInt(); to

int input = -1; 

That will kill the 1 percent chance of the random number being same as the number entered before the loop (game) starts , or maybe u can put an if condition checking if input and the random number are equal , if they are take a new random number and check again(in a loop)

CodePudding user response:

With the statement int input = kbd.nextInt(); before the while loop you are already waiting for user input - without prompting the user. I bet you application is waiting for you to enter the first int. Since you are waiting for while loop to start and the application is waiting for you there is a deadlock.

Figure out how to run a debugger to execute your code step by step. It will help a lot.

  • Related