我正在尝试为我的频道制作一个IRC机器人.我希望机器人能够从控制台获取命令.为了使主循环等待用户输入我添加循环的东西:
while(!userInput.hasNext());
Run Code Online (Sandbox Code Playgroud)
这似乎不起作用.我听说过BufferedReader,但我从未使用它,也不确定这是否能够解决我的问题.
while(true) {
System.out.println("Ready for a new command sir.");
Scanner userInput = new Scanner(System.in);
while(!userInput.hasNext());
String input = "";
if (userInput.hasNext()) input = userInput.nextLine();
System.out.println("input is '" + input + "'");
if (!input.equals("")) {
//main code
}
userInput.close();
Thread.sleep(1000);
}
Run Code Online (Sandbox Code Playgroud)
Ran*_*niz 12
您无需检查可用的输入等待和休眠,直到有Scanner.nextLine()阻止直到有线可用为止.
看看我写的这个例子来演示它:
public class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while (true) {
System.out.println("Please input a line");
long then = System.currentTimeMillis();
String line = scanner.nextLine();
long now = System.currentTimeMillis();
System.out.printf("Waited %.3fs for user input%n", (now - then) / 1000d);
System.out.printf("User input was: %s%n", line);
}
} catch(IllegalStateException | NoSuchElementException e) {
// System.in has been closed
System.out.println("System.in was closed; exiting");
}
}
}
Run Code Online (Sandbox Code Playgroud)
请输入一行
hello
等待1.892s进行用户输入
用户输入为:hello
请输入一行
^ D
System.in已关闭; 退出
所以你要做的就是使用Scanner.nextLine(),你的应用程序将等到用户输入换行符.你也不想在循环中定义你的扫描仪并关闭它,因为你将在下一次迭代中再次使用它:
Scanner userInput = new Scanner(System.in);
while(true) {
System.out.println("Ready for a new command sir.");
String input = userInput.nextLine();
System.out.println("input is '" + input + "'");
if (!input.isEmpty()) {
// Handle input
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24857 次 |
| 最近记录: |