简体   繁体   English

在Java中到达行尾的最后一行

[英]reach the last line with end of line in java

Scanner console = new Scanner(System.in);
String line = "";
String pera = " ";

System.out.println("Enter the text : ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(isr);
int lineNum = 0;
do {
    line = buf.readLine();
    System.out.println();
    pera = line + "";
    lineNum++;
    System.out.print(lineNum + " " + pera);
} while (line != null);
isr.close();
buf.close();

input : Hello world I am a file Read me until end-of-file. 输入:世界您好我是一个文件,直到文件结束为止,请读我。

output : 1 Hello world 2 I am a file 3 Read me until end-of-file. 输出:1 Hello world 2我是文件3读我直到文件结束。

and this code output is : 1 Hello world 2 I am a file 3 Read me until end-of-file. 并且此代码输出为:1 Hello world 2我是一个文件3读我直到文件结束。 4 null 4 null

Let's simplify things. 让我们简化一下。 You can assign a variable in a while loop. 您可以在while循环中分配变量。 Read lines one by one in it until it comes to end. 逐行读取其中的一行,直到结束。 We understand this when the BufferedReader reads a null line using (line = br.readLine()) != null . BufferedReader使用(line = br.readLine()) != null读取空行时,我们理解这一点。

System.out.println("Enter the text: ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int lineNo = 0;
String line;
while ((line = br.readLine()) != null) {
    System.out.println(++lineNo + " " + line);
}
isr.close();
br.close();

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

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