import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Reading integer input
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
System.out.println("You entered: " + number);
// Reading string input
System.out.print("Enter a string: ");
String text = scanner.next();
System.out.println("You entered: " + text);
scanner.close();
}
}
Enter an integer: 27
You entered: 27
Enter a string: Learning
You entered: Learning
Scanner
object by passing System.in
as a parameter to its constructor. This creates a scanner that can read input from the standard input stream, which is usually the keyboard.nextInt()
method of the Scanner class to read an integer input from the user, and the next()
method to read a string input. Finally, we close the Scanner
object using the close()
method to free up resources.