0

作为我作业的一部分,我需要制作一个需要用户输入的程序。现在我坚持使用控制台,但是我想避免由于换行符而导致的崩溃。

这是一个测试,它的行为类似于我正在尝试做的事情,甚至由于一个换行符而崩溃

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 回答