I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.
How can I get the user input in Java?
I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.
How can I get the user input in Java?
One of the simplest ways is to use a
Scanner
object as follows:Add
throws IOException
besidemain()
, thenHere is a more developed version of the accepted answer that addresses two common needs:
Code
Example
Note that without
nextLine()
, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to usenext()
instead depending on the circumstance, but know that input likethis has spaces
will generate multiple exceptions.Here is your program from the question using
java.util.Scanner
:I like the following:
and for example, I would do: