geting a multiline text with scanner class in java

Kasra Ghavami picture Kasra Ghavami · Nov 21, 2014 · Viewed 10.1k times · Source

In a part of my university project I have to get a text with some lines then saving it in a string or a string array.My problem is that in scanner class using methods gets only one line of the input. So I cannot get the other lines.please help me.

public class Main {
public static void main(String[] args) {
    java.util.Scanner a = new java.util.Scanner(System.in);
    String b = "";
    while (a.hasNextLine()) {
        b += a.nextLine();
    }
}

}

Answer

Yohanes Khosiawan 许先汉 picture Yohanes Khosiawan 许先汉 · Nov 21, 2014

You can try to use isEmpty to detect an enter-only input.

UPDATED:

If your input also contain a blank line, then you may specify another terminator character(s); instead of only an empty string.

public class Main {
    public static void main(String[] args) {
        //for example ",,"; then the scanner will stop when you input ",,"
        String TERMINATOR_STRING = ",,"

        java.util.Scanner a = new java.util.Scanner(System.in);
        StringBuilder b = new StringBuilder();
        String strLine;
        while (!(strLine = a.nextLine()).equals(TERMINATOR_STRING)) {
            b.append(strLine);
        }
    }
}