我的代码没有按预期工作,它必须使用 System.in.read() 方法执行某些操作。该程序旨在从控制台读取数据,直到我按“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);
}
}
输出为
D:\ex\1>java Input
d
d
c
c
D:\ex\1>
为什么输出中有空行
最佳答案
当您第一次调用 read
时,它会读取 'd'
并换行打印(因为您使用了 println
打印
)。这解释了第一条新线。循环第一次迭代后,再次调用read
。这次,它读取回车符'\r'
。第三次调用 read
时,它会读取换行符 '\n'
。这就是为什么有 3 条新线。
Where do those new line characters come from?
每次输入一个字符时,都会按回车键,对吗?这就是新线!由于您使用的是 Windows,因此它会插入 \r\n
。在我的 Mac 上,新行只是 \n
。这就是为什么您的代码在我的 Mac 上运行时会生成 2 个新行而不是 3 个新行。
解决这个问题的方法是不读取新行:
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);
或者您可以使用扫描仪
:
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);
关于java - 一个简单的java程序输出与IO不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40780298/