JAVA Input Validation for Number Range and Numeric values only with counter

若如初见. 提交于 2019-12-06 07:21:54

As others have said to see if a String is a valid integer you catch a NumberFormatException.

try {
    int number = Integer.parseInt(input);
    // no exception thrown, that means its a valid Integer
} catch(NumberFormatException e) {
    // invalid Integer
}

However I would also like to point out a code change, this is a prefect example of a do while loop. Do while loops are great when you want to use a loop but run the condition at the end of the first iteration.

In your case you always want to take the user input. By evaluating the while loops condition after the first loop you can reduce some of that duplicate code you have to do prior to the loop. Consider the following code change.

int count = 0;
String input;
int range;
do {
    input = JOptionPane.showInputDialog(quantity);
    try {
        range = Integer.parseInt(input);
    } catch(NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Sorry that input is not valid, please choose a quantity from 1-9");
        count++;
        // set the range outside the range so we go through the loop again.
        range = -1;
    }
} while((range > 9 || range < 1) && (count < 2));

if (count == 2) {
    JOptionPane.showMessageDialog(null, 
            "Sorry you failed to input a valid response, terminating.");
    System.exit(0);
}
return range;

This line:

int range = Integer.parseInt(input);

appears before your while loop. So, you know how to convert the input to an int. The next step is to realize that you should do it each time the user gives you an input. You are almost there.

If input string does not contain a valid number format in string then this line will throw NumberFormatException

int range = Integer.parseInt(input)

You need to put it try catch block

try {
            Integer.parseInt("test");
        } catch (java.lang.NumberFormatException e) {
                count++; //allow user for next attempt.
              //    showInputDialog HERE
              if(count==3) {
                // show your msg here in JDIalog.
              System.exit(0);
           }
}

For 3 chances to input the correct information, you need to use loop, inside loop call your showInputDialog method

As of JDK 1.8, you can use the temporal package to solve this, along-with the try-catch as shown by rest of the answers from this thread:

import java.time.temporal.ValueRange;
...
public static void main (String[] args){
ValueRange range = ValueRange.of(1,9);

    int num, counter = 0;

    do {
    System.out.print("Enter num: ");
    num = Integer.parseInt(scanner.next());
    if (range.isValidIntValue(num))
        System.out.println("InRange");
    else 
        System.out.println("OutOfRange");

    counter ++;
    } while (!range.isValidIntValue(num) && counter < 3);
...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!