system.in.read 未命中执行 [英] system.in.read miss execution

查看:26
本文介绍了system.in.read 未命中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在第一个循环之后,switch 会执行两次,然后才会停下来等待我的输入?标准输入中是否有任何字符?我该如何解决这个问题?

Why after the first loop, the switch will execute twice before it stop to wait for my input? Is there any char left in the standard input? How can I fix the issue?

while(true)
{
int choice = System.in.read();
switch(choice)
{
   case '1':
       break;
   default:
       break;
}
}

推荐答案

InputStream#read 只读取单个 byte 并且不会消耗换行符(将是 2 个字符,LFCR 在 Windows 平台上),将其传递到下一个 read.此 read 现在将阻塞接收到的输入,并且流程将落入您的 default 案例.

InputStream#read only reads a single byte and will not consume the newline character (will be 2 characters, LF and CR on Windows platforms), passing it through to the next read. This read will now not block having received input and the flow will fall through to your default case.

您可以使用 BufferedReader 代替并阅读整行:

You could use a BufferedReader instead and read a full line:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
...
int choice = Integer.parseInt(br.readLine());

这篇关于system.in.read 未命中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆