【问题标题】:how do i stop a infinite loop using char(input from keyboard method-System.in.read( ). System.in?如何使用 char 停止无限循环(从键盘输入方法-System.in.read(). System.in?
【发布时间】:2016-12-09 12:38:33
【问题描述】:
class Copied{
    public static void main(String args[])     throws java.io.IOException {  
        int i;  
        System.out.println("Press S to stop.");  
        for(i = 0; (char) System.in.read() != 'S'; i++)    
            System.out.println("Pass #" + i);
    } 
}

我无法得到预期的结果。

【问题讨论】:

  • 对我来说很好。你的预期结果是什么?或者您是否对每个输入字符的双“Pass #”输出感到困惑?
  • 预期结果是什么?我希望上述循环在进入 S 时停止。
  • 我想要一个无限循环,在按下 S 后停止,这样我就不必在某些输出后按 Enter 键

标签: java loops input


【解决方案1】:

上面的代码比较棘手的是

(char) System.in.read() != 'S'

.read()

从输入流中读取数据的下一个字节。值字节是 返回为int 范围内的0255

因此,您的输入被视为:

Input : a
Output  : Pass #0 // for a
Pass #1 //for Enter


Input : all
Output : Pass #2 // a
Pass #3 //l
Pass #4 //l
Pass #5 // Enter

对于任何字符串也是如此,除非它包含一个字符S

Input : stingWithSHere
Output : Pass #6 //s
Pass #7 //t
Pass #8 //i
Pass #9 //n
Pass #10 //g
Pass #11 //W
Pass #12 //i
Pass #13 //t
Pass #14 //h

然后它终止。希望这能让事情看起来很清楚。


严格限制用户的输入,您可以改为使用 -

new Scanner(System.in).next(".").charAt(0) != 'S'

对于更新后的问题,@Tom 分享的链接现在可以回答 -

How to get input without pressing enter every time?

【讨论】:

  • 实际上我希望循环继续进行,除非我输入“S”,这样我就不必在某些显示后按 Enter 我希望它继续我们可以这样做,但这个也是对我有帮助,谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-06-20
  • 2015-04-25
  • 2022-08-24
  • 2015-02-04
  • 2012-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多