我有一个用户输入验证函数:
public int UserChoiceValidate() {
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.print("Please enter your choice: ");
while (!sc.hasNextInt()) {
System.out.print("Input invalid, please retry: ");
sc.nextLine(); // consume left over
}
choice = sc.nextInt();
if (choice <= 0 || choice > 5) {
System.out.println("Choice not included, please retry");
}
} while (choice <= 0 || choice > 5);
return choice;
}
代码将重复
Input invalid, please retry:输入无效,please retry:输入无效,please retry:
当我垃圾输入然后键入无效的输入时
我如何修复这个错误,而不必重写它为读取String而不是int。我有相当多的函数具有相同的结构,我希望避免重写它们。
我不确定你所说的"将其重写为字符串验证"是什么意思,你目前忽略了用户提供的不是int
的任何输入;如果您想处理",请输入spam"特别的,你可以这样写
System.out.print("Please enter your choice: ");
while (!sc.hasNextInt()) {
String line = sc.nextLine();
if (line.isEmpty()) {
continue;
}
System.out.print("Input invalid, please retry: ");
}