-1

Hi I want to do something in java. I have a scanner, if the user gives us a number I do something if it's a string I do something else. It works with but not like I want, because when I give a int like 12 java knows that's it's a number but when I give something like 12.5 he thinks it's string.

Scanner in = new Scanner(System.in);
        if(in.hasNextDouble()){
            System.out.println("number");
        }else if(in.hasNextLine()){
            System.out.println("text");
        }

thx

Userlambda
  • 85
  • 1
  • 11

2 Answers2

2

You can use regular expression to validate your input:

Scanner in = new Scanner(System.in);
String line = in.nextLine();
Pattern p = Pattern.compile("[0-9]+([.]([0-9]+))?");
if(p.matcher(line).matches()){
    System.out.println("number");
} else {
    System.out.println("text");
}
Nam Tran
  • 643
  • 4
  • 14
  • it works fine, know i realize the importance of regular expression. – Userlambda Nov 08 '17 at 10:35
  • This behaviour could be problematic depending on what you want to do. If you want the user to enter only a number, or only text, this will not work as expected. The regex will tell you if there is a number in the text, so if you typed `hello 2.0 world`, it would match. You then try to read a double from the input, and get a parse exception. Regex by default is greedy, and it's often more complicated to get the rightr output than anticipated. – Alex Nov 08 '17 at 11:50
  • The following regex will match only a number, so `hello 2.0 world` will not match, but `2.0` will. - `^[0-9]+([.]([0-9]+))?$` - explained : the caret at the start marks the start of the string, the dollar sign marks the end of the string. – Alex Nov 08 '17 at 11:52
0

Define a local for the scanner to tell it what decimal formatting to use

 // change the locale of the scanner
   in.useLocale(Locale.ENGLISH);

By default, it whichever locale is set as the default for your JVM, so if that is defined to use a comma separator, this will be expected on the scanner input. Setting the ENGLISH locale will use a dot, as will any other locale which uses a dot separator in decimal numbers.

Alex
  • 1,643
  • 1
  • 14
  • 32
  • This is partly correct. By default it uses comma separator **if that is the separator of your JVMs locale**. You can change the locale for the JVM, or just for the Scanner. If your JVMs locale is english, your Scanner will also use the dot as the default. – Raimund Krämer Nov 08 '17 at 14:08
  • @D.Everhard - Thats a good point. I'll ammend the answer for clarity – Alex Nov 08 '17 at 14:13