0

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

我浏览了很多教程并搜索了这方面的帮助,但一无所获。这是我的代码。

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: ");
        }  
4

2 回答 2

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: ");
    }  
}
于 2013-03-05T13:17:43.633 回答
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.
 }
于 2013-03-05T13:19:14.973 回答