java - 验证扫描仪输入时出错,包含两个带一个空格的单词
问题描述
尝试验证用户只需输入伪代码:word1 空格 word2。这似乎应该是一个简单的逻辑,如果字符串不等于 word1 空间 word2,再问一次。我已经构建了一个带有 if/else 逻辑的版本,可以正确捕获它,它只是不再询问。所以我尝试修改以使用 do while 循环。
Scanner sc = new Scanner(System.in);
System.out.print("Enter a two word phrase with one space.");
String phrase = sc.nextLine();
phrase = phrase.trim();
int i1 = phrase.indexOf(" ");
int i2 = phrase.indexOf(" ", i1 +1);
do{
System.out.println("Enter a two word phrase with one space, Try Again!");
phrase = sc.nextLine();
}while(i2 != -1);
System.out.println("Correct");
}
这段代码的结果是它只需要输入两次,并且无论输入什么都以正确结尾。
解决方案
在您的 do-while 循环中,该值i2
永远不会更新。
int i1 = phrase.indexOf(" ");
int i2 = phrase.indexOf(" ", i1 +1);
在您的 while 循环之外,因此 i2 永远不会更新,因此 while 循环不能也不会结束。
因此,这部分属于循环:
Scanner sc = new Scanner(System.in);
String phrase;
int idx;
do {
System.out.println("Enter a two word phrase with one space!");
phrase = sc.nextLine().trim();
int spaceIdx = phrase.indexOf(" ");
idx = phrase.indexOf(" ", spaceIdx + 1);
} while(idx != -1);
System.out.println("Correct");
推荐阅读
- triggers - 当创建相关商机时触发更新客户中的自定义字段,其值与商机的自定义字段中的值相同
- java - 设置数组的值不起作用 - 为什么?
- javascript - 移动菜单(CSS 和 JavaScript)未打开
- amazon-web-services - 如何在 AWS API Gateway WebSocket 中将数组解析为正文?
- c - 创建 Windows API 以从命令行添加、修改、查询、删除注册表项
- c - Difference in printing out pointer value vs array
- legend - Vega - 独特图表上的多个图例
- java - 为什么我无法正确预览抽屉式导航菜单?
- c# - Program.Main(string[])' 的签名错误,无法作为项目的入口点格式
- javascript - pdf.js - javascript 中的页面淡入/淡出效果