【问题标题】:Error verifying scanner input contains two words with one space验证扫描仪输入时出错,包含两个带一个空格的单词
【发布时间】:2021-05-09 13:28:36
【问题描述】:

试图验证用户是否输入了伪代码: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");
        }
 

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

【问题讨论】:

  • i2 in while body 从不更新,始终保持与第三行相同。

标签: java string loops validation java.util.scanner


【解决方案1】:
    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");

【讨论】:

  • 效果很好。我还有另一个测试用例,如果用户输入三个带有两个空格的单词,它还需要要求用户再试一次。我尝试在 while 循环之外添加 int i3 = phrase.indexOf(" ", i2 + 1); 和 `i3 = phrase.indexOf(" ", i2 + 1);'里面,但如果我输入 word1 空格 word2 空格 word3 它仍然返回正确。
  • 您可以创建一个字符串数组,其中包含输入字符串(短语)的拆分字符串。:如果有一个空格,则数组长度为 2。如果有 2 个空格,则为三个。
  • String[] 控制器 = 短语.split(" "); System.out.println(controller.length);
  • 您在空格处拆分您的短语 (" ")
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 2019-11-08
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    相关资源
    最近更新 更多