在按Enter键之前检查用户是否输入任何内容 [英] Check if user input anything before pressing enter

查看:166
本文介绍了在按Enter键之前检查用户是否输入任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个基本的java控制台应用程序,我想在输入之前检查用户是否提供了任何输入。我正在使用Scanner类来获取输入。现在我得到的是,每当我按下回车而没有输入任何东西时,应用程序只是等待输入。

I am doing a basic java console application and I want to check if the user provided any input before pressing enter. I'm using the Scanner class to get the input. Right now all I get is that the application just waits for input whenever I press enter without typing in anything.

推荐答案

您可以进入等待输入的循环。如果用户按Enter键,检查输入,如果没有提供输入,则继续循环。如果提供了输入,则从循环中断。

You can go in a loop that waits for enter. If the user presses enter, check for input, if no input is provided, continue the loop. If input was provided, break from the loop.

如果您希望机制是非锁定的,则需要一个单独的线程。

If you want the mechanism to be non-locking, you need a separate thread.

Scanner input = new Scanner(System.in);
String s = null;
while ( true )
{
   s = input.nextLine();
   if( !s.equals("\\n") ) 
      break;
}

这篇关于在按Enter键之前检查用户是否输入任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆