java 等待输入_如何让Java等待用户输入

您无需检查可用的输入等待和休眠,直到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");

}

}

}

Please input a line

hello

Waited 1.892s for user input

User input was: hello

Please input a line

^D

System.in was closed; exiting

因此,您所要做的就是使用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

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值