Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 验证扫描仪输入包含两个带一个空格的单词时出错_Java_String_Loops_Validation_Java.util.scanner - Fatal编程技术网

Java 验证扫描仪输入包含两个带一个空格的单词时出错

Java 验证扫描仪输入包含两个带一个空格的单词时出错,java,string,loops,validation,java.util.scanner,Java,String,Loops,Validation,Java.util.scanner,正在尝试验证用户是否只输入了psuedo代码:word1 space word2。这似乎应该是简单的逻辑,若字符串不等于word1空格word2,请再次询问。我已经用if/else逻辑构建了一个版本,它正确地捕获了它,只是不再询问。因此,我尝试修改以使用do while循环 Scanner sc = new Scanner(System.in); System.out.print("Enter a two word phrase with one spa

正在尝试验证用户是否只输入了psuedo代码:word1 space 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
永远不会更新

inti1=phrase.indexOf(“”);
int i2=短语.indexOf(“,i1+1);
在while循环之外,因此i2永远不会更新,因此while循环不能也不会结束

因此,这部分属于循环:

Scanner sc=新扫描仪(System.in);
字符串短语;
int-idx;
做{
System.out.println(“输入一个带空格的两个单词的短语!”);
短语=sc.nextLine().trim();
int spaceIdx=短语.indexOf(“”);
idx=短语.indexOf(“,空格idx+1);
}而(idx!=-1);
系统输出打印项次(“正确”);

i2在第三行中,虽然body从未更新,但始终保持不变。这非常有效。我还有另外一个测试用例,如果用户输入了三个带两个空格的单词,它还需要要求用户再试一次。我试图添加
inti3=phrase.indexOf(“,i2+1”)在while循环之外,并且'i3=phrase.indexOf(“,i2+1);'在内部,但如果我输入word1 space word2 space word3,它仍然返回正确。您可以创建一个字符串数组,其中包含输入字符串(短语)的拆分字符串。使用一个空格,数组长度将为2。有两个空格的地方是三个。String[]controller=phrase.split(“”);System.out.println(控制器长度);您在空格(“”)处拆分短语
    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");