【问题标题】:Java: possible to stop scanner from pausing the consoleJava:可以阻止扫描仪暂停控制台
【发布时间】:2021-11-17 16:42:10
【问题描述】:

尝试创建一个小程序,它可以通过控制台接受输入,同时也可以通过它输出数据。我为它使用了一个循环,但每当我尝试添加向控制台输入信息的功能时,它就会把程序弄乱。

本质上代码是这样的

//outputting stuff to the console. All works fine

if(scanner.hasNext() && scanner.nextLine() != null){
   String input = scanner.nextLine();
}

这包含在循环中,用于输出内容的位也可以这样做。问题是,每当我添加有关扫描仪的位时,循环就会停止循环。那么有什么方法可以阻止扫描仪停止输出循环的其余部分,或者基本上是一种方法可以使我不必按回车键来再次循环。

编辑:这是整个代码段,以便更好地诊断。 reader 是来自另一部分代码的 inputStream。

while (true){
            String input = self.reader.nextLine();
            Scanner in = new Scanner(System.in);
            String[] subbed = input.split(" ");
            switch (subbed[0].toLowerCase()) {
                case "setid":
                    self.setPlayerID(Integer.parseInt(subbed[1]));
                    System.out.println("Player ID set to: " + self.playerID);
                    break;
                case "server":
                    System.out.println(input.replaceAll(subbed[0] + " ", ""));
                    break;

            }
            if(in.hasNext()){
                String out = in.nextLine();
            }

        }

【问题讨论】:

  • 您可以添加您的扫描仪声明吗?
  • Scanner scanner = new Scanner(System.in)
  • 试试这个:if(scanner.hasNext()){ String input =scanner.nextLine(); }
  • 仍然挂起输入而不是继续。在提交至少 1 个字符之前不会继续。这让我非常难过。

标签: java loops input


【解决方案1】:

这里似乎不太对劲,您的“self.reader”到底是什么,因为阅读器接口/inputStreams 没有定义 nextLine()。 无论如何,忽略代码的第一部分,Scanner 旨在阻止..因此,如果您希望它不阻塞,则需要用线程包装它。即

class ScanThread extends Thread {
    private Scanner scanner;
    private volatile String scanLine;
    
    public ScanThread(Scanner scanner){
        this.scanner = scanner;
    }

    public String getLine(){
        return scanLine;
    }

    public void run() {
        while(true) {
            System.out.println("CONSOLE NEXT LINE PLEASE:");
            scanLine = scanner.nextLine();
        }
    }
}

然后当你创建你的扫描仪时:

ScanThread threadedScanner = new ScanThread(new Scanner(System.in));
threadedScanner.start();

线程从你做的扫描仪读取:

threadScanner.getLine()

这将返回用户在控制台上输入的“最后一行”。 (如果用户从未按 Enter 键,则为 null)。在这个循环中,这将向输出发送垃圾邮件!,所以不确定你在这里真正寻找什么,祝你好运。

【讨论】:

    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    相关资源
    最近更新 更多