简体   繁体   English

Java - 如何在一个输入中输入多行文本

[英]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.我目前正在 Java 中编写一个程序,其中我需要从用户那里获取输入,这是一段文本。 However, I need the user to be able to enter multiple paragraphs of text in one go.但是,我需要用户能够在一个 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.我正在使用扫描仪进行输入,当我将多个段落粘贴到输入中时,不会抛出任何错误,但是每当我打印出存储文本的变量时,只有第一部分(在第一个换行符之前)是 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.从空字符串和 append 开始,每行输入的文本,直到用户用一些预先确定的字符集指示他完成了。

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.但是,如果您想阅读如此大的文本,则可以使用BufferedReader并简单地阅读到 stream 的末尾。 The end of the stream is reached when EOF is encountered.遇到 EOF 时到达 stream 的末尾。 On many systems an EOF can be generated by hitting Control-D (but you might want to indicate that to a user).在许多系统上,可以通过点击 Control-D 来生成 EOF(但您可能希望向用户表明这一点)。

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.使用这种通用方法的一大优点是,您还可以使用各种操作系统提供的实用程序将 pipe 文件放入您的应用程序中。

A disadvantage is that it is not a good idea to mix this with a Scanner ;一个缺点是,将它与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.显然扫描仪在 EOF 之后是无用的,在文本之前使用它可能意味着扫描仪检索到部分文本。 Closing the scanner will also close the input stream it is connected to.关闭扫描仪也将关闭它所连接的输入 stream。 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().您可以使用 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?)我用 THE-END 作为标记做了一个小例子(是的,不是原始的吗?)

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.使用多个中断作为结束标记可能会更好(一些基于文本的协议会这样做),例如用户按回车键 3 次。 That would mean they cannot have two empty lines, so pretty use case dependent.这意味着它们不能有两个空行,因此非常依赖于用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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