Blank input from scanner - java

后端 未结 4 1986
梦毁少年i
梦毁少年i 2020-12-18 11:16

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

相关标签:
4条回答
  • 2020-12-18 11:38

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

    0 讨论(0)
  • 2020-12-18 11:43

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

    0 讨论(0)
  • 2020-12-18 11:54

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

    0 讨论(0)
  • 2020-12-18 11:55

    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.

    0 讨论(0)
提交回复
热议问题