Sing Sandibar
Sing Sandibar

Reputation: 714

How to tell my if-statement to only accept integers?

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
}

Upvotes: 0

Views: 7597

Answers (2)

NominSim
NominSim

Reputation: 8511

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;
    }
}

Upvotes: 0

assylias
assylias

Reputation: 328598

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();

Upvotes: 8

Related Questions