0

I want my program to tell the user that if (s)he enters a non-integer he should try again, instead of just terminating the whole main method like it does now. Pseudo code of problem part:

int integer = input.nextInt();
If (user types in a non-integer) { 
  ("you have entered a false value, please retry");
  then let's user enter int value
else {
  assign nextint() to integer and continue
}
Mat
  • 202,337
  • 40
  • 393
  • 406
Sing Sandibar
  • 714
  • 4
  • 15
  • 26
  • Use do-while loop as explained in answer below by assylias & use commons apache's StringUtils class to determine if input is integer or not. – Jeevan Patil Sep 28 '12 at 16:15

2 Answers2

8

You can use a while loop to re-execute that portion of code until the user enters a proper integer value.

do {
    input = read user input
} while(input is not an integer)

It seems you are using a Scanner, so you could use the hasNextInt method:

while (!input.hasNextInt()) {
    let user know that you are unhappy
    input.next(); //consume the non integer entry
}

//once here, you know that you have an int, so read it
int number = input.nextInt();
assylias
  • 321,522
  • 82
  • 660
  • 783
0

This is assuming that you are worried about the user entering in something other than an integer on input:

public static void main(String[] args) {
    Integer integer = 0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter an integer:");
    String line = sc.next();
    integer = tryParse(line);
    while(integer == null){
        System.out.print("The input format was incorrect, enter again:");
        integer = tryParse(sc.next());
    }
    int value = integer.intValue();
}

public static Integer tryParse(String text){
    try{
        return new Integer(text);
    } catch
    (NumberFormatException e){
        return null;
    }
}
NominSim
  • 8,447
  • 3
  • 28
  • 38