Java 从System.in.read()读取时出现问题
我刚刚了解到,当按下enter键响应Java 从System.in.read()读取时出现问题,java,Java,我刚刚了解到,当按下enter键响应系统.in.read()时,以下字符会被放入控制台缓冲区\r\n。因此,当我将以下1输入终端并按enter键时,计算机将该语句读取为1\r\n。那么System.out.println(“hello”)不应该执行两次吗?因为choice将存储值1。然后,将打印“hello”。然后,ignore将保存值\r。然后,控件将在(忽略!='\n')循环时被赋予while。然后,ignore将保存值\n。然后,将打印“hello”。现在,ignore=\n,代码将跳出循
系统.in.read()
时,以下字符会被放入控制台缓冲区\r\n
。因此,当我将以下1
输入终端并按enter键时,计算机将该语句读取为1\r\n
。那么System.out.println(“hello”)
不应该执行两次吗?因为choice
将存储值1
。然后,将打印“hello”。然后,ignore
将保存值\r
。然后,控件将在(忽略!='\n')循环时被赋予while。然后,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;
}
}
}
类帮助类演示{
公共静态void main(字符串参数[])
抛出java.io.IOException{
选择,忽略;
对于(;;){
做{
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.继续\n”);
系统输出打印(“选择一个(q退出):”;
choice=(char)System.in.read();
做{
ignore=(char)System.in.read();
System.out.println(“你好”);
}while(忽略!='\n');
}而(选项<'1'|选项>'7'&choice!='q');
如果(选项=='q')中断;
}
}
}
我认为代码是否有\r
(回车)、\n
(新行)或两者都有\r\n
取决于平台
我在windows机器上运行了你的代码,它确实打印了两次hello
您可能需要检查正在使用的机器以及为该环境定义的行分隔符。详情请参阅
有关以下内容的帮助:
1.如果
2.转换
3.对于
4.虽然
5.暂且
6.打破
7.持续
选择一个(q退出):1
选择1
你好
你好
你从哪里学到的?是什么让你认为这是真的?当您实际尝试并记录调用read
的每个结果的值时,您得到了什么?您的问题是什么?为什么要使用System.in.read()
?你应该用微笑来感谢你!