gpt4 book ai didi

java - 设置整数输入的边界

转载 作者:行者123 更新时间:2023-12-01 14:47:56 24 4
gpt4 key购买 nike

我有一小段代码,在运行时需要用户输入以确定某个值。我不希望用户能够输入小于 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: ");
}

最佳答案

添加一个简单的 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: ");
}
}

关于java - 设置整数输入的边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15224765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com