Java User Input (Scanner)
Java User Input (Scanner)
To take input from the user in Java, we use the Scanner class, which is part of the java.util package.
Before using it, you must import it:
Then create a Scanner object:
Example: Taking a String Input
✔ Output:
Input Methods in Scanner
| Method | Use |
|---|---|
nextLine() |
Reads whole line (including spaces) |
next() |
Reads a single word |
nextInt() |
Reads an integer |
nextDouble() |
Reads a decimal number |
nextFloat() |
Reads a float |
nextBoolean() |
Reads a boolean (true/false) |
nextLong() |
Reads a long value |
Example: Number Input
Taking Multiple Inputs
⚠️ Important: Using nextLine() After nextInt()
When mixing numeric and string inputs, nextInt() leaves a newline (\n) in the buffer.
So after using nextInt(), add one nextLine():
Example: Simple Calculator using User Input
🏁 Summary
✔ Use Scanner to take input from the user
✔ Different methods exist for different data types
✔ Use nextLine() after nextInt() (or similar) to avoid input issues
