我创建了一个方法来查看用户输入的值是否为 int
类型介于 liminf
之间和limsup
。它返回值,以便我可以将其用作菜单选项。
字符串message
告诉用户输入一些内容,error
告诉用户使用 limunf
之间的数字和limsup
.
我的问题是,例如,如果用户输入数字 10 和 liminf
是 7 和 limsup
e 9,它的运行方式就像数字 10 位于 limsup
之间和liminf
.
public static int readInput(String message, String error, int liminf, int limsup, Scanner rd){
int option = 0;
do {
option = rd.nextInt();
System.out.println(message);
while (!rd.hasNextInt()) {
System.out.println("Please enter the option");
rd.nextLine();
}
option = rd.nextInt();
canal.nextLine();
} while (option > limsup || option < liminf);
return option;
}
最佳答案
当您检查输入时,您需要做两件事:
- 检查该值是否确实是一个整数
- 检查该值是否在范围内
要检查值是否为整数,您可以使用两种方法之一。使用hasNextInt
在您的Scanner
上,或使用Integer.parseInt
并捕获NumberFormatExceptions
。您在评论中说不能使用第二个,所以我们将使用第一个。
您总是需要调用hasNextInt
在你打电话之前请先调用nextInt
,所以你可以这样做:
int option = 0;
System.out.println(message);
System.out.println("Please enter the option");
while (!rd.hasNextInt()) {
rd.nextLine(); // Clears the invalid input
System.out.println("Please enter the option");
}
option = rd.nextInt();
这将循环直到用户输入 int
,那么就会得到int
。注意不要打电话hasNextInt
在调用nextInt
之前将导致错误,如果您尝试输入非数字,则会在当前代码中发生错误。
接下来,您需要进行边界检查。您希望它介于 limsup
之间和liminf
,其中limsup > liminf
, 如果我没错的话。我们需要确定允许这样做的条件。
Between是通过使用大于较低的数字和小于较高的数字来实现的。在本例中,即 option >= liminf && option <= limsup
。我们想要在不是这个的时候循环,所以我们可以将整个事情包装在 !()
中。 :
int option = 0;
do {
System.out.println(message);
System.out.println("Please enter the option");
while (!rd.hasNextInt()) {
rd.nextLine(); // Clears the invalid input
System.out.println("Please enter the option");
}
option = rd.nextInt();
} while (!(option >= liminf && option <= limsup));
return option;
我会让您弄清楚如何/在哪里打印错误消息,但这应该可以帮助您开始。
值得注意的是:
-
hasNextInt
,nextInt
,nextLine
如果您使用Scanner rd = new Scanner(System.in);
等,将全部等待用户输入 - 使用
nextLine
有必要清除旧输入并强制用户输入新输入 - 虽然德摩根定律很酷,但反转条件的最简单方法就是将其包装在
!()
中。
关于java - 如何检查输入是否为 int 且位于两个值之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13609121/