简体   繁体   English

一个简单的Java程序输出与IO所不同

[英]A simple java program output is not as expected with IO

i've a code which is not working as expected, it has to do something with System.in.read() method. 我有一个未按预期工作的代码,它必须使用System.in.read()方法执行某些操作。 the program is meant to read from the console until i press 'c' or 'C' 该程序旨在从控制台读取,直到我按“ c”或“ C”

import java.io.*;

public class Input{
    public static void main(String args[])throws IOException{
        char b;

        outer:
        do{
            b= (char)System.in.read();
            System.out.println(b);
            if(b=='c'||b=='C'){
               break outer;
            }
        } while(true);      
    }
}

output is 输出是

D:\ex\1>java Input
d
d



c
c

D:\ex\1>

why are there empty lines in the output 为什么输出中有空行

When you call read the first time, it reads 'd' and prints it with a new line (because you used println instead of print ). 第一次调用read时,它将读取'd'并用新行将其打印(因为您使用了println而不是print )。 This explains the first new line. 这解释了第一行。 After the loop's first iteration, read is called again. 在循环的第一次迭代之后,再次调用read This time, it reads the carriage return character '\\r' . 这次,它读取回车符'\\r' The third time read is called, it reads the new line character '\\n' . 调用第三次read ,它将读取换行符'\\n' That's why there are 3 new lines. 这就是为什么有3条新线的原因。

Where do those new line characters come from? 这些换行符从哪里来?

Each time you enter a character, you press "enter" right? 每次输入一个字符时,您都按“输入”对吗? That's the new line! 那是新线! Since you're using Windows, it inserts \\r\\n . 由于您使用的是Windows,因此会插入\\r\\n While on my Mac, a new line is just \\n . 在Mac上,换行只是\\n That's why your code produces 2 instead of 3 new lines when run on my Mac. 这就是为什么在Mac上运行时,您的代码生成2行而不是3行的原因。

The solution to this is not to read the new lines: 解决方案是不读取新行:

do{
     b= (char)System.in.read();
     if (b == '\r' || b == '\n') continue;
     System.out.println(b);
        if(b=='c'||b=='C'){break outer;}

}while(true);

Or you can use a Scanner : 或者您可以使用Scanner

char b;
Scanner sc = new Scanner(System.in);
outer:
do{
    b= sc.findWithinHorizon(".", 0).charAt(0);
    System.out.println(b);
    if(b=='c'||b=='C'){break outer;}

}while(true);

simply replace System.out.println(b); 只需替换System.out.println(b); with

int a = (int) b;
if (a != 13 && a != 10) {
    System.out.println(b);
}

it will not print the char, if the int value of it is line feed and carriage return 如果它的int值是换行和回车,它将不打印字符

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

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