来自扫描仪的空白输入 - java
我想做的是,如果用户单击回车键,程序应该抛出 BadUserInputException。 我的问题是,每当我按下回车键时,它只会将我置于控制台的另一行中,基本上什么也不做。
Scanner input = new Scanner(System.in);
System.out.println("Enter Student ID:");
String sID = null;
if (input.hasNextInt()==false){
System.out.println("Please re-check the student number inputted. Student number can only be digits.");
throw new BadUserInputException("Student number can not contain non-digits.");
}else if (input.next()==""){
throw new BadUserInputException("Student number can not be empty");
}
What I'm trying to do is if the user clicks on the enter key the program should throw a BadUserInputException.
My problem is whenever I press the enter key it just puts me in another line in the console essentially doing nothing.
Scanner input = new Scanner(System.in);
System.out.println("Enter Student ID:");
String sID = null;
if (input.hasNextInt()==false){
System.out.println("Please re-check the student number inputted. Student number can only be digits.");
throw new BadUserInputException("Student number can not contain non-digits.");
}else if (input.next()==""){
throw new BadUserInputException("Student number can not be empty");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我遇到了这个确切的问题,并且我相信我找到了解决方案。
关键是接受 String 类型的输入,并使用
.isEmpty()
方法检查用户是否输入了任何内容。如果您的字符串被命名为“cheese”并且您的扫描器被命名为“in”,则如下所示:
我尝试对整数输入实现此检查,发现最好接受字符串类型输入并使用包装类将其转换为 int 类型。如果您有
,那么您可以将此代码放在上面的
else
语句中:我知道这个问题是在 2 年前提出的,但我发布此问题是为了帮助像我这样正在寻找解决方案的其他人回答。 :)
I am encountering this exact problem, and I believe I figured out a solution.
The key is to accept input as type String and use the
.isEmpty()
method to check whether the user entered anything or not.If your String is named "cheese" and your scanner is named "in", here's what this looks like:
I tried implementing this check for integer input and discovered it's better to accept String type input and convert it to int type with a wrapper class. If you have
then you would put this code in the
else
statement above:I am aware that this question was asked 2 years ago, but I posted this in hopes of helping others like myself who were looking for an answer. :)
扫描器会查找空格和换行符之间的标记 - 但没有任何标记。我不倾向于使用 Scanner 从标准输入读取 - 我使用老式的 BufferedReader 方法,如下所示:
然后我可以说
可能有一个更简单的解决方案然而。
The scanner looks for tokens between whitespaces and newlines - but there aren't any. I don't tend to use
Scanner
for reading from standard input - I use the old-fashionedBufferedReader
method like this:and then I can say
There may be an easier solution however.
只需在扫描字符串时使用
nextLine()
方法而不是next()
即可,最后使用isEmpty()
方法检查字符串。这对我有用..Just use
nextLine()
method instead ofnext()
while scanning the String and finally check the string usingisEmpty()
method. This Worked for me..您需要使用
.equals
方法而不是==
来比较字符串。You need to compare strings with the
.equals
method, not==
.