我正在 Windows 7 上编写 Java,我希望能够使用键盘输入,我只能假设这是标准输入。
我尝试过使用 BufferedInput
、System.in
和 Scanner
,但它们都需要程序暂停并等待换行或返回!有没有办法只收集和记录使用的数据,而不必等待返回?
最佳答案
这是一个快速解决方案:
public static void main(String[] args) {
Thread inputThread = new Thread(new Runnable() {
@Override
public void run() {
Scanner scan = new Scanner(System.in);
String input = "";
while (true) {
System.out.println("Type something: ");
input = scan.nextLine();
System.out.println("Input: "+input);
}
}
});
inputThread.start();
while (true) {
System.out.println("");
System.out.println("test");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
主线程每秒打印“test”。 inputThread 要求用户输入一些内容,然后打印他所写的内容。这只是一个“视觉”解决方案,您当然不想在用户打字时打印某些内容。
关于java - 从键盘获取输入而不暂停程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9348803/