Mastering Java - Full Guide
Collect User Input With Scanner
Collect User Input With ScannerTo collect input from the user in Java, you typically use the Scanner class. First, you need to import it at the top of your file:
import java.util.Scanner;Then, create a Scanner object and use its methods to read input. For example, here’s how to read an integer:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // create scanner object
System.out.print("Enter a number > ");
int num = sc.nextInt(); // waits for user input
System.out.println("You entered " + num);
}
}OUTPUT:
Enter a number > 123
You entered 123Note: nextInt() method leaves a newline (\n) in the buffer stream after you call it.
Collect Doubles
To collect a decimal number, use nextDouble(). This method leaves a newline (\n) in the buffer stream after you call it.
Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 14 more lessons in Mastering Java - Full Guide.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.