简体   繁体   English

如何在Java中同时读取多行作为输入

[英]how to read multiple lines as input at the same time in java

I want to input a paragraph (multiple lines) at the same time (not one line by one line) in Java. 我想在Java中同时输入一个段落(多行)(而不是一行一行)。 I want to add "the line number is :" to each line I input in command prompt, and exit it when the input is null. 我想在命令提示符下输入的每一行中添加“行号为:”,并在输入为null时退出。 The code below is my attempt. 下面的代码是我的尝试。

I tried to research on Internet, but I am still confused with Scanner and BufferedReader. 我曾尝试在Internet上进行研究,但仍然对Scanner和BufferedReader感到困惑。

How do I adjust my program? 如何调整程序?

import java.io.*;

public class Word {

    public static void main(String[] args) throws IOException{
        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader input=new BufferedReader(is);
        String s=input.readLine();
        int lineNum=1;
        while(s!=null&&s.length()>0) {

            System.out.println("Line number "+lineNum+" : "+s);
            lineNum++;

        }
    }
}

In your code you cast the user input to variable "s" once before the loop. 在您的代码中,在循环之前将用户输入强制转换为变量“ s”。 In the loop "s" never changes so there's no exit condition, and it will always print the exact same line. 在循环中,“ s”永不更改,因此没有退出条件,它将始终打印完全相同的行。 You have to put the line String s=input.readLine(); 您必须将String s=input.readLine(); in the loop, so each time it will read a new line from the user. 在循环中,因此每次它将从用户读取新行。

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

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