Input/Output In Java
The Scanner class is a subclass of the java.util package, allows to user to take input in Java programs. The Scanner class provides ways to scan different user inputs, including text, integers, doubles, and more. Here’s a step-by-step tutorial for using the Scanner class to capture user input.
1. Import the Scanner Class
The Scanner class must first be imported, so add the following import statement to the top of your Java file
import java.util.Scanner;
2. Create a Scanner Object
Create the object of the Scanner class by using the new Keyword
Scanner scanner = new Scanner(System.in);
3. Reading Input from the User
The Scanner class has a number of methods that can be used to read various forms of input. Here are a few illustrations
To read a line of text (a string) from the user
System.out.print(“Enter your name: “);
String name = scanner.nextLine( );
4. For Reading an Integer
System.out.print(“Enter your age: “);
int age = scanner.nextInt( );
5. For Reading double/float from the user
System.out.print(“Enter a decimal number: “);
double number = scanner.nextDouble( );
Explore more by clicking the link below