检查输入数字是否为正整数的最简单方法是什么?如果不是,则重新提示?

时间:2014-01-23 04:03:15

标签: java validation

程序接受用户输入,该输入应该是大于0的整数。如果用户不这样做,则会通知他错误并被重新提示。输入正确的输入后,将返回该值。最好的方法是什么?以下代码是我的尝试,但不起作用。对于这么简单的任务来说,这似乎是不必要的复杂。

    System.out.println("Please enter an integer greater than 0:");
    Scanner scan = new Scanner(System.in);
    int red = -1;
    do
    {
        try
        {
            red = scan.nextInt();
        }catch(InputMismatchException e)
        {
            System.out.println("Number must be an integer"); 
            scan.nextLine();
            if(red < 1)
                System.out.println("Number must be more than zero");
            else
                break;
        }
    }while(true);
    return red;

有时候我不知道在我的问题中放什么,因为我已经知道代码不起作用 - 所以如果还有别的我应该告诉我,请告诉我。

2 个答案:

答案 0 :(得分:0)

基本概念是朝着正确的方向运行,但要注意,nextInt不会消耗新行,将其留在扫描仪中,这意味着在第一次不成功的循环后,您将最终得到无限循环。

就个人而言,我只是使用String将输入作为nextLine获取,这将使用新行,导致下一个循环停止在语句处。

然后我只需使用String

int解析为Integer.parseInt

例如......

Scanner scan = new Scanner(System.in);
int red = -1;
do {
    System.out.print("Please enter an integer greater than 0:");
    String text = scan.nextLine();
    if (text != null && !text.isEmpty()) {
        try {
            red = Integer.parseInt(text);
            // This is optional...
            if (red < 1) {
                System.out.println("Number must be more than zero");
            }
        } catch (NumberFormatException exp) {
            // This is optional...
            System.out.println("Not a number, try again...");
        }
    }
} while (red < 1);

答案 1 :(得分:0)

我使用此类而不是ScannerBufferedReader类来获取用户输入:

import java.io.*;
public class Input{
private static BufferedReader input=new BufferedReader
                (new InputStreamReader(System.in));
public static Double getDouble(String prompt){
    Double value;
    System.out.print(prompt);
    try{
        value=Double.parseDouble(Input.input.readLine());
    }
    catch (Exception error){
        // error condition
        value=null;
    }
    return value;
}
public static Integer getInteger(String prompt){
    Integer value;
    System.out.print(prompt);
    try{
        value=Integer.parseInt(Input.input.readLine());
    }
    catch (Exception error){
        // error condition
        value=null;
    }
    return value;
}
public static String getString(String prompt){
    String string;
    System.out.print(prompt);
    try{
        string=Input.input.readLine();
    }
    catch (Exception error){
        // error condition
        string=null;
    }
    return string;
}
}

现在,为了回答你的问题,你可以像这样编写你的代码:

public class InputTest {


public int checkValue() {

    int value; 
    do {
        value = Input.getInteger("Enter a value greater than 0: ");
    } while (value <= 0);

    return value;

    }
   }