Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟢 Foundation  ·  Lesson 09

User Input in Java using Scanner

In this lesson: Read int, double, String and lines with Scanner in Java, fix the nextLine trap and practise 3 programs with real output. Hindi & English.

Reading input in Java

To make a program interactive, it must read input from the user. In Java, the easiest way is the Scanner class. You create a Scanner tied to the keyboard (System.in) and use its methods to read text and numbers.

💡 Scanner reads different types: nextInt() for whole numbers, nextDouble() for decimals, nextLine() for text.

Import and create Scanner

import java.util.Scanner;   // at the top

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // ready to read input
    }
}

First import java.util.Scanner;, then create Scanner sc = new Scanner(System.in);. System.in means the keyboard. Now sc can read what the user types.

Reading text and numbers

String name = sc.nextLine();   // whole line of text
String word = sc.next();       // one word
int    age  = sc.nextInt();    // whole number
double pay  = sc.nextDouble(); // decimal number

Each method reads a specific type. Use nextLine() for text with spaces, next() for a single word, and nextInt()/nextDouble() for numbers.

A complete example

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = sc.nextLine();

        System.out.print("Enter your age: ");
        int age = sc.nextInt();

        System.out.println("Hi " + name + ", age " + age);
        sc.close();
    }
}
Enter your name: Aman
Enter your age: 18
Hi Aman, age 18

We prompt, read a name and an age, then print them. sc.close() at the end frees the Scanner.

The nextLine after nextInt bug

int age = sc.nextInt();
sc.nextLine();              // FIX: consume leftover newline
String name = sc.nextLine();

A classic trap: after nextInt(), the Enter key is left in the buffer, so the next nextLine() reads an empty line. The fix is one extra sc.nextLine() right after the number, to swallow that leftover newline.

Practice programs with Scanner

These three programs are common in school and college practical files. Each was compiled with javac and run with the input shown (typed values appear after each prompt).

Program 1: Sum and average of three numbers

import java.util.Scanner;

public class SumAverage {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter three numbers: ");
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        int sum = a + b + c;
        double avg = sum / 3.0;
        System.out.println("Sum = " + sum);
        System.out.printf("Average = %.2f%n", avg);
        sc.close();
    }
}
Enter three numbers: 12 15 20
Sum = 47
Average = 15.67

nextInt() can read several numbers typed on one line, separated by spaces. Dividing by 3.0 (not 3) gives a decimal average.

Program 2: Marksheet – name, 5 subjects, percentage and grade

import java.util.Scanner;

public class Marksheet {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Student name: ");
        String name = sc.nextLine();
        int total = 0;
        for (int i = 1; i <= 5; i++) {
            System.out.print("Marks in subject " + i + ": ");
            total += sc.nextInt();
        }
        double percent = total / 5.0;
        String grade = percent >= 90 ? "A1" : percent >= 75 ? "A2" : percent >= 60 ? "B1" : percent >= 33 ? "C" : "Needs improvement";
        System.out.println(name + ": total " + total + "/500, " + percent + "%, grade " + grade);
        sc.close();
    }
}
Student name: Riya Sharma
Marks in subject 1: 88
Marks in subject 2: 92
Marks in subject 3: 79
Marks in subject 4: 95
Marks in subject 5: 84
Riya Sharma: total 438/500, 87.6%, grade A2

The name is read first with nextLine(), before any nextInt(), so the newline trap does not occur. The ternary chain picks the grade.

Program 3: Simple interest calculator

import java.util.Scanner;

public class SimpleInterest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Principal (Rs): ");
        double p = sc.nextDouble();
        System.out.print("Rate (% per year): ");
        double r = sc.nextDouble();
        System.out.print("Time (years): ");
        double t = sc.nextDouble();
        double si = p * r * t / 100;
        System.out.printf("Simple interest = Rs %.2f%n", si);
        System.out.printf("Total amount = Rs %.2f%n", p + si);
        sc.close();
    }
}
Principal (Rs): 25000
Rate (% per year): 7.5
Time (years): 3
Simple interest = Rs 5625.00
Total amount = Rs 30625.00

nextDouble() reads decimal values such as 7.5; printf("%.2f") prints money with two decimal places.

Try it yourself: change Program 2 to read the number of subjects from the user, and Program 3 to also print the interest for each year.

Common mistakes

  • Forgetting the import. You must import java.util.Scanner; at the top.
  • The nextLine-after-nextInt bug. Add an extra sc.nextLine() to fix it.
  • Using next() for full names. next() stops at a space — use nextLine().
  • Wrong method for the type. Reading text with nextInt() throws an error.

Summary

  • Use the Scanner class to read user input.
  • Import it, then create new Scanner(System.in).
  • nextInt(), nextDouble(), next(), nextLine() read different types.
  • Fix the newline bug with an extra nextLine() after nextInt().
  • Close the Scanner with sc.close() when done.

Next, use the input in decisions with if-else, or process it in Java loops.

Frequently Asked Questions

How do I take input from the user in Java?
Use the Scanner class. Import it with import java.util.Scanner;, create it with Scanner sc = new Scanner(System.in);, then read values with methods like sc.nextInt() and sc.nextLine().
What is the difference between next() and nextLine()?
next() reads a single word (stopping at a space), while nextLine() reads the whole line including spaces. Use nextLine() when the input can contain spaces, like a full name.
How do I read a number in Java?
Use nextInt() for whole numbers and nextDouble() for decimals. These read the number directly, so you do not need to convert from text yourself.
Why does nextLine() get skipped after nextInt()?
nextInt() leaves the newline (Enter) in the input buffer, and the next nextLine() reads that leftover newline as an empty line. The fix is to add an extra sc.nextLine() to consume it.
Do I need to close the Scanner?
It is good practice to call sc.close() when you are done reading input, to free resources. For small programs it is not critical, but it is a clean habit.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicIf-Else Statements Your progress: 9 / 61 (15%) · Lesson 10 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free