简体   繁体   中英

Java multiline scanner input

I have a specific problem regarding Scanner and its way of doing input from System.in .

What I want to do: I need to read a single input given from System.in . The problem is that this input can have more than one line (the input can have many \\n characters).

What I tried:

The obvious thing I tried is Scanner.nextLine() method, but ofcourse, this will not read all data. The next thing I tried is this:

Scanner sc = new Scanner(System.in);
List<String> data = new ArrayList<>(); 

while(sc.hasNextLine()){
    String line = sc.nextLine();
    if(line.isEmpty()){
        break;
    }
    data.add(line);
}

But this will also skip a lot of data - for instance, when there is an empty line in the middle of given text.

I also tried to remove the break; statement and hope that the while(sc.hasNextLine()) loop will break itself, but this will never happen since scanner will wait for the data.

Can this be done in Java? Thanks for your time

If you press Command + D on OS X or Control + D on Windows, you will insert an end of line character.

When the scanner reaches an end of line character, hasNextLine will return false and the loop will terminate.

So remove this:

if(line.isEmpty()){
    break;
}

and type an end of line character after your multi line input.

Alternatively, if this is allowed, you can put your input as a string to the scanner. For example, if you want to input this input:

Hello World
This is a
Multiline
input

You can initialise the scanner like this:

Scanner line = new Scanner("Hello World\n" +
        "This is a\n" +
        "Multiline\n" +
        "input");

Or you can put your input into a file and let the scanner read that:

Scanner line = new Scanner(new File("path to your input file"));

Use this type for reading

String read = "";
    Scanner sc = new Scanner(System.in);
    String line;
    while (sc.hasNextLine()) {
        line = sc.nextLine();
        if (line.isEmpty()) {
            break;
        }
        read += line + "\n";
    }
    System.out.println(read);

Here, first we check is there nextline occurs or not. if yes then read data using sc.nextLine() method and if read data is blank then break loop.

If you want to read all input, on multiple lines, into a list of strings, one element per input line, then the user will have to indicate when the input has ended. This is often done by using the End-of-File character: on the Windows Command Prompt, it's Ctrl-Z, and on Linux, OS X and the IntelliJ IDE input window on all platforms, it's Ctrl-D.

You can read the lines with the following code:

Scanner sc = new Scanner(System.in);
List<String> data = sc.tokens().collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM