设置整数输入的边界

时间:2013-03-05 13:15:41

标签: java input limit

我有一小段编码,在运行时需要用户输入以确定某个值。我不希望用户能够输入小于0且大于1百万的任何内容,因此,0 =< YEARS_AHEAD =<百万。

我查看了很多教程,并在此搜索了一些帮助,却一无所获。这是我的代码。

Scanner reader = new Scanner(System.in);
    int YEARS_AHEAD;
    System.out.print("Enter the amount of years ahead: ");
    while (true)
        try {
            YEARS_AHEAD = Integer.parseInt(reader.nextLine());
            break;
        }catch (NumberFormatException nfe) {
            System.out.print("This value must be an integer, please enter the number of years ahead again: ");
        }  

2 个答案:

答案 0 :(得分:1)

添加简单的if:

if (YEARS_AHEAD < 0 || YEARS_AHEAD > 1000000) {
  // say something to the user, retry entering the number
}

另一个选择是使用while循环:

int YEARS_AHEAD = -1; // invalid value
while (YEARS_AHEAD < 0 || YEARS_AHEAD > 1000000) {
    try {
        System.out.print("Enter the amount of years ahead: ");
        YEARS_AHEAD = Integer.parseInt(reader.nextLine());
    }catch (NumberFormatException nfe) {
        System.out.print("This value must be an integer, please enter the number of years ahead again: ");
    }  
}

答案 1 :(得分:0)

阅读完输入后

YEARS_AHEAD = Integer.parseInt(reader.nextLine());

使用if-else检查是否允许输入。

if(YEARS_AHEAD < 0 || YEARS_AHEAD >1000000){
   System.out.println("Invalid Input");
  }else{
     // do your processing here.
 }