如何从用户读取字符串直到遇到换行符(Java)?

时间:2018-03-01 22:22:50

标签: java string newline

所以问题是我想要读取字符串的多行并将它们放入ArrayList中,只要用户没有输入任何内容就不会进入下一行。

以下是示例输入的内容:

hello 
I am John

这是我尝试的代码,但它没有用。 (错误是:"字符串索引超出范围:0"。)

Scanner input = new Scanner(System.in);
ArrayList<String> text = new ArrayList<>();
while (true) {
    String temp = input.nextLine();
    if (temp.charAt(0) == '\n') {
        break;
    }
    text.add(temp);
}

3 个答案:

答案 0 :(得分:3)

您可以尝试if (temp.isEmpty()),因为Scanner会读取一个空字符串。

Scanner input = new Scanner(System.in);
List<String> text = new ArrayList<>();
while (true) {
    String temp = input.nextLine();
    if (temp.isEmpty()) break;
    text.add(temp);
}

答案 1 :(得分:1)

nextLine() 删除行终止符。见Javadoc。

你应该测试为空的行

答案 2 :(得分:1)

您可以使用https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html

方法readLine而不是Scanner。

 === Positive test cases:
PASS    "-foo"
 --> Parsed: (foo  )
PASS    "-foo           -bar"
 --> Parsed: (foo bar )
PASS    "-foo-want"
 --> Parsed: (foo  want)
PASS    "-foo -meow-bar"
 --> Parsed: (foo bar meow)
PASS    "-foo-mix-mustache"
 --> Parsed: (foo mustache mix)
PASS    "-handle      -foo-meow"
 --> Parsed: (foo handle meow)
PASS    "-mustache-foo"
 --> Parsed: (foo mustache )
PASS    "-mustache -mix -foo"
 --> Parsed: (foo mustache mix)
PASS    "-want-foo"
 --> Parsed: (foo  want)
FAIL    "-want-meow-foo"
FAIL    "-want-foo-meow"
 === Negative test cases:
PASS    "woof"
PASS    "-handle-meow"
PASS    "-ha-foondle"
PASS    "meow"
PASS    "-foobar"
PASS    "stackoverflow"
PASS    "- handle -foo -mix"
PASS    "-handle -mix"
PASS    "-foo -handle -bar"
PASS    "-foo -handle -mix -sodium"