Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to take input from user using Scanner class.

Java Code Example — Input/Output Programs

ADVERTISEMENT

Java Program to take input from user using Scanner class.

Objective

Write a Java program to take user input interactively using the Scanner class.

Algorithm / Approach

  1. Import the java.util.Scanner class.
  2. Create a Scanner object hooked to the standard input stream: Scanner s = new Scanner(System.in);.
  3. Use s.nextLine() to read a full string of text.
  4. Use s.nextInt() to read an integer.
  5. Use s.nextDouble() to read a decimal number.
  6. Print the collected values.
InputDemo.java
import java.util.Scanner;
class InputDemo{
 public static void main(String[] a)
 {		
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Name: ");
  String name = s.nextLine();
  System.out.print("Enter Age: ");
  int age = s.nextInt();
  System.out.print("Enter Marks: ");
  double m=s.nextDouble();
  System.out.println("Name- "+name);
  System.out.println("Age- "+age);
  System.out.println("Marks- "+m);
 }
}

Expected Output

Enter Name: Ayan
Enter Age: 2
Enter Marks: 97
Name- Ayan
Age- 2
Marks- 97.0

Explanation of the Program

  • The Scanner class is the most common and easiest way for beginners to handle interactive I/O in Java.
  • It abstracts away the complex byte-parsing logic required to read from System.in (the keyboard) and automatically tokenizes the input based on whitespace.
  • It provides convenient methods like nextInt() and nextDouble() so you don't have to manually parse strings into numbers like you do with command-line arguments.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Calling nextLine() immediately after nextInt() without clearing the buffer. The nextLine() will consume the leftover newline character and skip user input.
ADVERTISEMENT