Concept

How do you read numeric input from a user in Java with Scanner?

ComputerScienceOne / Converting Units

"Scanner s = new Scanner(System.in); The variable s is now active and can be read from. You can get specific values from the Scanner by calling various methods such as s.nextInt() to get an int, s.nextDouble() to get a double, etc. When these methods are called, the program blocks until the user enters her input and presses the enter/return key. The conversion to the type you requested is automatic. A full example is depicted in Code Sample 26.2.\n\nOne potential problem with using Scanner is that the methods cannot force a user to enter good input. In the example above, if the user, instead of entering a number, entered \"Hello\", the conversion to a number would fail and result in a InputMismatchException.\n\nScanner s = new Scanner(System.in);\n\nint a;\n\nSystem.out.println(\"Please enter a number: \");\n\na = s.nextInt();\n\nSystem.out.printf(\"Great, you entered %d\n\n\", a);"

Related Ideas