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
- How can a Java program read income and children inputs while rejecting negative values?ComputerScienceOne · Life & Taxes
- How do you catch and handle an exception in Java?ComputerScienceOne · Catching Exceptions
- Why must you use floating-point division when converting Fahrenheit to Celsius in Java?ComputerScienceOne · Converting Units
- What is 26?ComputerScienceOne · Computing Quadratic Roots
- How can PHP read and clean user input from standard input?ComputerScienceOne · Converting Units
- How does scanf() read integer, character, and floating-point input in C?ComputerScienceOne · Basic I/O
- How can a Java program compute a logarithm in an arbitrary base?ComputerScienceOne · Computing a Logarithm
- How are command line arguments accessed and converted in Java?ComputerScienceOne · The javamain() Method