Scanner HasNextLine总是返回false

问题描述 投票:3回答:2

我正面临Scanner.hasNextLine()这个奇怪的问题。我不使用Scanner类,但习惯于使用Scanner.hasNextLine()作为循环获取连续用户输入的条件,但是在这部分代码中,它始终返回false!

public static void main(String[] args) throws IOException {
    String s = "";
    Scanner ssc = new Scanner(System.in);
    Client cli = new Client();
    cli.HLO();
    Thread t = new Thread(new ThreadMessage(cli));//Thread that asks user for input using Scanner and closing it then
    t.start();
    boolean b = ssc.hasNextLine();
    while (true) {
        b = ssc.hasNextLine();
        System.out.println(b);
        if (b) {
            s = ssc.nextLine();
            System.out.println("you wrote" + s);
            cli.dp.setData(s.getBytes());
            cli.ds.send(cli.dp);
        }
    }
}

并且作为输入,我只有一个带有单词false的行循环

有人知道为什么会这样吗?

编辑:似乎错误来自使用另一台扫描仪的HLO功能,我删除了它,现在它正确地发了言。

java java.util.scanner
2个回答
2
投票

尝试使用.hasNext()方法而不是.hasNextLine()方法。您遇到了问题,因为.hasNextLine() 如果此扫描仪的输入中有另一行,则方法返回true。但是,如果此扫描程序的输入中包含另一个令牌,则.hasNext()方法将返回true。

参考:http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html


0
投票

就我而言,我的代码中有多个Scanner(System.in)实例,这些代码被多个人触摸。

如果这些实例之一调用“ close”,它将全部关闭,并且不会重新打开文件。

在关闭后调用hasNextLine()始终将返回false。

© www.soinside.com 2019 - 2024. All rights reserved.