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
- Import the
java.util.Scannerclass. - Create a Scanner object hooked to the standard input stream:
Scanner s = new Scanner(System.in);. - Use
s.nextLine()to read a full string of text. - Use
s.nextInt()to read an integer. - Use
s.nextDouble()to read a decimal number. - 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
Scannerclass 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()andnextDouble()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 afternextInt()without clearing the buffer. ThenextLine()will consume the leftover newline character and skip user input.