Home > Software engineering >  Stay in a loop until the right input
Stay in a loop until the right input

Time:10-23

Im trying to build a simple guessing game where you choose the range of numbers. I want to stay in my loop until the user guesses the right number. The while loop allows no next input after the first wrong guess. How do I stay inside of a loop until a variable matches?

import java.util.Scanner;
public class main {
public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    test random = new test();
    
    System.out.print("Please input a minumum amount: ");
    int min = reader.nextInt();
    System.out.print("Please input a maximum amount: ");
    int max = reader.nextInt();
    
    int answer = random.getRandom(min, max);
    
    System.out.print("Please guess a number between you "   min   "-"   max   ": ");
    int input = reader.nextInt(); 
    
    while(input != answer) {
            System.out.println("Guess again");
    }
    
    if(input == answer) {
        System.out.println("You got it right!");
    }
    
    
}
}

CodePudding user response:

while(true){
if(input==answer) break;
else continue;
}

CodePudding user response:

Isn't the line "input = reader.nextInt();" where you get the input from the user? If so, then that line also needs to be inside the while loop so you can get another guess from the user. But don't use the definition "int" the second time, or you will get an "already defined" error.

Also, isn't the "if(input == answer) {" test unnecessary, since if the answer were not correct you'd still be in the while loop?

  • Related