【发布时间】:2015-10-17 02:57:34
【问题描述】:
我刚刚了解到,当按下回车以响应System.in.read() 时,会将以下字符放入控制台缓冲区\r\n。因此,当我在终端中输入以下1 并按回车键时,计算机将该语句读取为1\r\n。那么System.out.println("hello")不应该被执行两次吗?因为choice 将存储值1。然后,"hello" 将被打印出来。然后,ignore 将保存值\r。然后,控件将被赋予while(ignore != '\n') 循环。然后,ignore 将保存值\n。然后,"hello" 将被打印出来。现在ignore = \n,代码会跳出循环吗?
class HelpClassDemo {
public static void main(String args[])
throws java.io.IOException {
char choice, ignore;
for(;;) {
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. for");
System.out.println(" 4. while");
System.out.println(" 5. do-while");
System.out.println(" 6. break");
System.out.println(" 7. continue\n");
System.out.print("Choose one (q to quit): ");
choice = (char) System.in.read();
do {
ignore = (char) System.in.read();
System.out.println("hello");
} while(ignore != '\n');
} while(choice < '1' | choice > '7' & choice != 'q');
if(choice == 'q') break;
}
}
}
【问题讨论】:
-
你从哪里学来的?是什么让你认为这是真的?当您实际尝试并记录调用
read的每个结果的值时,您得到了什么?你有什么问题? -
你为什么使用
System.in.read()?你应该使用Scanner
标签: java