Blank input from scanner - java

2019-01-27 06:13发布

问题:

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");
    }

回答1:

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:

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]
}

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

then you would put this code in the else statement above:

else{
eger = Integer.valueOf(cheese);
}

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. :)



回答2:

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-fashioned BufferedReader method like this:

BufferedReader buf = new BufferedReader (new InputStreamReader (System.in));

and then I can say

String line = buf.readLine ();
if (line.equals ("")) blah();

There may be an easier solution however.



回答3:

Just use nextLine() method instead of next() while scanning the String and finally check the string using isEmpty() method. This Worked for me..



回答4:

You need to compare strings with the .equals method, not ==.