Re-prompt user after invalid input in Java

拟墨画扇 提交于 2019-11-30 16:59:26
s.ts

Replace if with while.

BAM, problem solved.

Use a while loop.

while (true) {
    System.out.println("What is your age?\n");
    age = userInput.nextInt();
    if ((age > 120) || (age < 1))
        System.out.println("ERROR Please enter a valid age\n");
    else
        break;
}

You could put it in to a while loop so that it keeps looping until the conditions are met --

System.out.println("What is your age?\n");
age = userInput.nextInt();

while((age > 120) || (age < 1)) {//error message
    System.out.println("ERROR Please enter a valid age");
    System.out.println("");
    System.out.println("What is your age?\n");
    age = userInput.nextInt();
}//end if

use do-while:

boolean valid;
do {
     System.out.println("What is your age?\n");
     age = userInput.nextInt();
     valid = age > 1 && age < 120;
     if (!valid) {
       System.out.println("ERROR Please enter a valid age");
     }
}while (!valid);

What about this

---->One time check - is your input is empty or just pressed the spacebar

Scanner scnr = new Scanner(System.in);      
System.out.println("Enter a string: ");
String input = scnr.nextLine(); 

boolean isEmpty = input == null || input.trim().length() == 0;
if (isEmpty){
    System.out.println("Enter a string again: ");
    input = scnr.nextLine(); 
}

------> Multiple time check- is your input is empty or just pressed the spacebar

 Scanner scnr = new Scanner(System.in);       
do {
    System.out.println("Enter a string: ");
    input = scnr.nextLine();
}
     while (input == null || input.trim().length() == 0);

Important: Don't forget that input should be static string in this case.

static String input=""; 

// Using do-while loop, this problem can be tackled.

    do {
        System.out.println("Enter a pin: ");
        pin = sc.nextInt();
    } while (pin != 12345);
    System.out.println("Welcome to program");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!