待办列表搜索功能:限制用户输入单个单词的实现与问题解决
问题解决记录
我已经解决这个问题了!因为try-catch块的表现不符合预期,我直接把它移除了。以下是我的最终代码,感谢所有回复此问题的用户。
我正在开发一个待办列表程序,其中一个功能是在字符串数组中搜索条目。要求用户只能输入单个单词作为关键词,若用户输入多个单词或无内容,需提示用户重新输入。我最初在try-catch语句中编写代码,但使用Scanner的next()方法时,输入多词关键词只会截取第一个词,不会抛出异常,因此调整了实现逻辑。
最终实现代码
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; }
内容的提问来源于stack exchange,提问作者qwertyboi
相关产品推荐
相关产品推荐

