验证扫描仪输入包含两个单词和一个单词时出错 space

Error verifying scanner input contains two words with one space

正在尝试验证用户是否只是输入了伪代码:word1 space word2。这看起来应该是简单的逻辑,如果字符串不等于word1 space 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");
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a two word phrase with one space.");
    String phrase = sc.nextLine();
    phrase = phrase.trim();
    int i1 = phrase.indexOf(" ");
    int i2 = phrase.indexOf(" ", i1);
    while (i2 == -1) {
        System.out.println("Enter a two word phrase with one space, Try Again!");
        phrase = sc.nextLine();
        i1 = phrase.indexOf(" ");
        i2 = phrase.indexOf(" ", i1);
    }
    System.out.println("Correct");