首页 > 解决方案 > 验证扫描仪输入时出错,包含两个带一个空格的单词

问题描述

尝试验证用户只需输入伪代码: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");
        }
 

这段代码的结果是它只需要输入两次,并且无论输入什么都以正确结尾。

标签: javastringloopsvalidationjava.util.scanner

解决方案


在您的 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");

推荐阅读