0

I'm trying to only accept numbers from a user. This code works for giving them an error message if they enter a letter. But it doesn't work for if they hit Enter or just white space. I've tried initializing a String called test as null and then setting scnr.nextLine() = test, and then checking if test is empty, but I didn't understand how to keep the rest of the program operating correctly when I did that. Scanner is very tricky to me. Please help!

        double mainNumber = 0;

        System.out.print("Enter a number: ");

            if (scnr.hasNextDouble() ){
                mainNumber = scnr.nextDouble();
                System.out.println(mainNumber);
                scnr.nextLine();
            }
            else {
                System.out.println("Sorry, please enter a number.\n");
                scnr.nextLine();
            }
m0a
  • 1,005
  • 2
  • 15
  • 29
  • The purpose of the program is that I would take the value stored in mainNumber and perform a calculation with it, and then that would be the end. – m0a Sep 25 '15 at 15:33
  • 1
    Define "number"... there are integers, decimals, hexadecimal/octal/exponential/.. formatted numbers, negative, complex, irrational numbers, etc.. – Binkan Salaryman Sep 25 '15 at 15:35
  • 1
    I found at reference to ``Console#echo(boolean)`` in [this thread](http://stackoverflow.com/questions/8138411/masking-password-input-from-the-console-java) and that (private) method turns off the user input echo. With that you can write your own input mask for the console. – Binkan Salaryman Sep 25 '15 at 15:53

3 Answers3

4

You have to use while-cycle and loop input as long as needed before user put a valid number.

This code

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    double mainNumber = 0;
    boolean isValidNumber = false;

    System.out.print("Enter a number: ");
    while (isValidNumber == false) {
        String line = scnr.nextLine();
        try {
            mainNumber = Double.valueOf(line);
            isValidNumber = true;
        } catch (NumberFormatException e){
            System.out.print("Sorry, please enter a number.\n");
        }
    }

    System.out.println("Main number is: " + mainNumber);
}

Having this sample output :

Enter a number: sdfgsgxb
Sorry, please enter a number.
xcvbxcvb
Sorry, please enter a number.
gsfdfgsdf
Sorry, please enter a number.
aearg
Sorry, please enter a number.
15.77
Main number is: 15.77
libik
  • 22,239
  • 9
  • 44
  • 87
  • 1
    Good work, this is the answer I was preparing to submit. Alternatively, you can use a `do-while` loop with the same conditions, though that would prevent simple printing of an "error" message. – CubeJockey Sep 25 '15 at 15:38
3

Well I guess your code is in a while loop or something ? So that it keep asking until the user enter the right value.

Then you should (for convenience) use String str = scnr.nextString() instead of nextDouble() and analyze the string it returned.

You can use str.trim() to remove whitespaces (and then check if string is empty with str.isEmpty() ), and to check if it's a number you can use regexp ( How to check that a string is parseable to a double? and any regex tutorial you can find ) or just use this regex: str.matches("\\d+") (returns true if str is a number, but no comma here).

Of course, don't forget to cast your String as double after: Double.parseDouble( str.replace(",",".") );. I hope the "replace" part is obvious ;)

Community
  • 1
  • 1
Asoub
  • 2,273
  • 1
  • 20
  • 33
0

You might use the following snippet to read one double value:

Scanner scanner = new Scanner(System.in);
try {
    double number = Double.parseDouble(scanner.nextLine());
} catch (NumberFormatException e) {
    e.printStackTrace();
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142