Google News
logo
Java Program to Get Input from User
To get input from the user in Java, you can use the Scanner class. Here's an example program that reads an integer and a string input from the user:
Program :
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();
    }
}
Output :
Enter an integer: 27
You entered: 27
Enter a string: Learning
You entered: Learning
In this example, we first create a 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.

We then use the 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.