如何要求用户只输入一个字符串,并在try-catch块中产生错误提示


编辑:我想通了!我去掉了try-catch块,因为它没有按照我想要的方式工作。下面的代码是我的最后一个代码。感谢所有回答这个问题的人。

我正在尝试编写一个待办事项列表程序。这个程序的一个功能是搜索字符串数组中的条目。用户只应输入一个单词关键字,因此如果用户输入了多个单词或没有输入,则应显示提示,告诉用户重试。到目前为止,我编写的代码位于try-catch语句中。当输入多个单词的关键字时,使用next((scanner只获取第一个单词,而忽略其余单词,而不会产生Exception。这是我的代码:

case 2:
String searchKeyword;


int success = 0;

while(success==0) {
System.out.print(">> Enter 1 keyword: ");
searchKeyword = sc.nextLine();

String splitSearchKeyword[] = searchKeyword.split(" ");

if (splitSearchKeyword.length == 1) {
if(Quinones_Exer2.searchToDoList(searchKeyword, todoList)==-1) {
System.out.println(">> No item found with that keyword!");
System.out.println();
}
else {
System.out.println(">> Found one item!");
System.out.println("("+(Quinones_Exer2.searchToDoList(searchKeyword, todoList)+1)+")"+" "+todoList[Quinones_Exer2.searchToDoList(searchKeyword, todoList)]);
System.out.println();
}
success++;
}
else {
System.out.println(">> Please input a single word keyword!");
System.out.println();
}
}
break;
}```

使用Scanner.nextLine((然后拆分提供的字符串。如果数组的长度大于1或提供的字符串为空,则发出无效输入消息,并让用户再次输入字符串:

while(tries2 == 0) {
searchKeyword  = "";
while (searchKeyword.isEmpty()) {
System.out.println("Enter 1 keyword: ");
searchKeyword = sc.nextLine().trim();
if (searchKeyword.isEmpty() || searchKeyword.split("\s+").length > 1) {
System.out.println("Invalid Entry! {" + searchKeyword 
+ "You must supply a single Key Word!");
searchKeyword = "";
}
}
tries2++;
// ... The rest of your code ...
}

来自Scanner.next((的文档:

从该扫描程序中查找并返回下一个完整的令牌。完整的标记前面和后面都是与分隔符模式匹配的输入。

您需要再次调用next()才能获得其余的输入。

更简单的方法是使用Scanner.nextLine((获取整行,然后使用String.split((和您正在使用的任何分隔符来获取所有输入关键字的数组。

编辑:扫描仪。next(模式(可以执行您想要的操作。如果输入与所提供的模式(regex(不匹配,它将抛出InputMismatchException。示例:

scanner.next("^[a-zA-Z]+$")

这要求整行由小写字母和/或大写字母组成,而不包含其他内容。

最新更新