简体   繁体   中英

How do I loop until the user put the correct input on java?

I'm writing this program and I want to display the message "Invalid machine number, please enter again" when the user puts a number that is not between 1000 and 2000. I'm trying to loop until the user puts the correct input but I can't. When I enter a correct number after entering an invalid one, it still displays the error message.

System.out.println("Enter Vending Machine number(number 1000-2000):");

int vendMachNo = scan.nextInt();

while(vendMachNo <1000 || vendMachNo >2000)
{
    System.out.println("Invalid machine number, please enter again");

    int VendMachNo = scan.nextInt();
    {

    }
 // ...

You've not reusing the variable, but creating a new one in a loop. It's not used anywhere:

int VendMachNo = scan.nextInt();

instead, you should reassign the one, that is checked in while loop:

vendMachNo = scan.nextInt();

Have a look,

    System.out.println("Enter Vending Machine number(number 1000-2000):");
    Scanner scan = new Scanner(System.in);
    int vendMachNo = scan.nextInt();
    while((vendMachNo < 1000 && vendMachNo > 2000)) {
        System.out.println("Invalid machine number, please enter again!");
        vendMachNo = scan.nextInt(); // reinitialize
    }
    System.out.println("Exiting!");

You are using 2 diferents variables VendMachNo and vendMachNo, java is key sensitive so you have a problem there.
Try this:

System.out.println("Enter Vending Machine number(number 1000-2000):");
int VendMachNo = scan.nextInt();

while(VendMachNo <1000 || vendMachNo >2000)
{
    System.out.println("Invalid machine number, please enter again");
    VendMachNo = scan.nextInt();
}

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