扫描仪的空白输入-Java [英] Blank input from scanner - java
问题描述
我想做的是,如果用户单击Enter键,则程序应引发BadUserInputException. 我的问题是,每当我按Enter键时,它只会使我进入控制台的另一行,而实际上什么也没做.
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");
}
推荐答案
我遇到了这个确切的问题,我相信我已经找到了解决方案.
I am encountering this exact problem, and I believe I figured out a solution.
关键是接受输入作为String类型,并使用.isEmpty()
方法检查用户是否输入了任何内容.
The key is to accept input as type String and use the .isEmpty()
method to check whether the user entered anything or not.
如果您的字符串被命名为"cheese",而扫描仪被命名为"in",则如下所示:
If your String is named "cheese" and your scanner is named "in", here's what this looks like:
cheese = ""; // empty 'cheese' of prior input
cheese = in.nextLine(); //read in a line of input
//if user didn't enter anything (or just spacebar and return)
if(cheese.isEmpty()) {
System.out.println("Nothing was entered. Please try again");
}
//user entered something
else {
[enter code here checking validity of input]
}
我尝试对整数输入执行此检查,发现最好接受String类型的输入,并使用包装器类将其转换为int类型.如果有
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
int eger = 0; //initialize to zero
然后将这段代码放在上面的else
语句中:
then you would put this code in the else
statement above:
else{
eger = Integer.valueOf(cheese);
}
我知道这个问题是2年前提出的,但是我发布了这个问题,希望是希望帮助像我这样的人寻找答案. :)
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. :)
这篇关于扫描仪的空白输入-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!