0

宿題の一環として、ユーザー入力を必要とするプログラムを作成する必要があります。今のところ私はコンソールに固執していますが、改行文字によるクラッシュを避けたいと思います。

これはテストです。これは、私がやろうとしていることと同じように動作し、改行文字が1つでもクラッシュします。

public void testRead() {

    Scanner input = new Scanner(System.in);

    String s1 = "", s2 = "", s3 = "", s4 = "", s5 = "";

    while (s1 == "" || s1 =="\n") 
        if (input.hasNext()) {
            s1 = input.nextLine();
        }
    while (s2 == "" || s2 =="\n") 
        if (input.hasNext()) {
            s2 = input.nextLine();
        }
    while (s3 == "" || s3 == "\n") 
        if (input.hasNext()) {
            s3 = input.nextLine();
        }
    while (s4 == "" || s4 == "\n") 
        if (input.hasNext()) {
            s4 = input.nextLine();
        }
    while (s5 == "" || s5 == "\n") 
        if (input.hasNext()) {
            s5 = input.nextLine();
        }
        // Here is why it might crash
    if (input.hasNextInt()) // even though it should not pass this if
            // However the if is not the issue. 
            // This input may even be in another function
           int crash = input.nextLine();

    System.out.println("s1: " + s1);
    System.out.println("s2: " + s2);
    System.out.println("s3: " + s3);
    System.out.println("s4: " + s4);
    System.out.println("s5: " + s5);
}

}

私はその声明がそれを解決することを望みましたwhileが、そうではありません。

クラッシュを解決することはできましたが、まだ空の文字列が残っているため、問題は解決しませんでした。

This is the first string
This is the second string
                                          <- pressed enter again, by mistake or not
This is the third string
This is the fourth string

出力

s1: This is the first string
s2: This is the second string
s3:
s4: This is the third string
s5: This is the fourth string

//クラッシュします。繰り返しになりますが、クラッシュは回避できますが、文字列3が読み取られていないか、含まれていないという問題があります。

この問題を解決する簡単な方法はありますか?簡単な方法がない場合は、それを無視して宿題を早く終えたいと思いますが、それでも将来の参考のために長い答えを知りたいと思います。

4

1 に答える 1

2

==文字列の内容の同等性には使用できません。例としてこれを試してください。

 while (s1.equals("") || s1.equals("\n")) 
        if (input.hasNext()) {
            s1 = input.nextLine();
        }
    while (s2.equals("") || s2.equals("\n")) 
        if (input.hasNext()) {
            s2 = input.nextLine();
        }
    while (s3.equals("") || s3.equals("\n")) 
        if (input.hasNext()) {
            s3 = input.nextLine();
        }
    while (s4.equals("") || s4.equals("\n")) 
        if (input.hasNext()) {
            s4 = input.nextLine();
        }
    while (s5.equals("") || s5.equals("\n")) 
        if (input.hasNext()) {
            s5 = input.nextLine();
        }
于 2012-12-27T12:48:07.447 に答える