简体   繁体   中英

Java - How to Input Multiple Lines of Text In One Input

I'm currently writing a program in Java in which I need to get input from the user, which is a piece of text. However, I need the user to be able to enter multiple paragraphs of text in one go. This would be achieved by simply pasting in the entire piece of text when the input is prompted by the program. I am using Scanner for the input, and at the moment when I paste multiple paragraphs into the input, no errors are thrown however whenever I print out the variable which the text was stored into, only the first section (before the first line break) is output. How can I store the entire piece of text with multiple line breaks without prompting the user for individual inputs for each block of text?

I have some code already but it doesn't handle multiple lines:

import java.util.*;

public class ReWrite {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please paste the essay to be re-written >> ");
    String originalEssay = scanner.nextLine();
    System.out.println(originalEssay);
    System.out.println("I hope that was your essay...");
  }
}

You need to have a way for the user to indicate when he is done entering data.

Until that happens, take the latest input line and save it. Start with an empty String and append each line of entered text until the user indicates with some pre-determined set of characters that he is done.

Generally you should not try to enter entire pieces of text from command line. However, if you want to read such a large piece of text then you can use a BufferedReader and simply read until the end of the stream. The end of the stream is reached when EOF is encountered. On many systems an EOF can be generated by hitting Control-D (but you might want to indicate that to a user).

Big advantage of using such a generic method is that you can also use various OS provided utilities to pipe a file into your application.

A disadvantage is that it is not a good idea to mix this with a Scanner ; obviously the scanner is useless after the EOF, and using it before the text will likely mean that the scanner retrieves part of the text. Closing the scanner will also close the input stream it is connected to. A scanner often has to look ahead to see where a token ends, and it may have to read into the text to be able to do so.

StringBuilder sb = new StringBuilder();

try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
    CharBuffer buffer = CharBuffer.allocate(1024);

    while (reader.read(buffer) != -1) {
        buffer.flip();
        sb.append(buffer);
        buffer.clear();
    }
}
System.out.printf("Read %d characters", sb.length());

I've not provided a character encoding. For such applications the platform character encoding should do just fine.

import java.util.*;

public class ReWrite {
    public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);

        System.out.println("Please paste the essay to be re-written >> ");

        String originalEssay = "";

        System.out.println();

        while(scanner.hasNextLine()){
             originalEssay += scanner.nextLine();
             originalEssay += "\n";
        }

        System.out.println(originalEssay);
        System.out.println("I hope that was your essay...");
    }
}

You need the above program. You need to make sure that you're checking if there are any other "lines" in the input. You do this by using hasWhileNext(). Hope this helps!

You need some way to know the user is done with their input. I made a small example with THE-END as marker (yeah, original isn't it?)

import java.util.Scanner;

public class DocReader {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder strBuilder = new StringBuilder();

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (!line.equals("THE-END")) {
                strBuilder.append(line + System.lineSeparator());
            } else {
                break;
            }
        }
        System.out.println(strBuilder.toString());
        scanner.close();
    }
}

This adds an extra line separator at the end, easy to solve that if needed. It would be probably better to use multiple breaks as an end marker (some text based protocols do that), eg the user press enter 3 times. That would mean they cannot have two empty lines, so pretty use case dependent.

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