0
0
Javaprogramming~5 mins

Using Scanner class in Java

Choose your learning style9 modes available
Introduction

The Scanner class helps your program read input from the keyboard or other sources easily.

When you want to ask the user to type their name.
When you need to get numbers or words from the user during the program.
When you want to read data from a file or text input.
When you want to make your program interactive by accepting user input.
Syntax
Java
import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

// To read a string
String text = scanner.nextLine();

// To read an integer
int number = scanner.nextInt();

// Close scanner when done
scanner.close();

Always import java.util.Scanner before using it.

Remember to close the scanner with scanner.close() to free resources.

Examples
This reads a full line of text from the user and stores it in name.
Java
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
This reads an integer number from the user and stores it in age.
Java
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
This reads a decimal number from the user and stores it in price.
Java
Scanner scanner = new Scanner(System.in);
double price = scanner.nextDouble();
Sample Program

This program asks the user to type their name and age, then prints a greeting message using that information.

Java
import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        scanner.nextLine(); // consume the leftover newline
        
        System.out.println("Hello, " + name + ". You are " + age + " years old.");
        
        scanner.close();
    }
}
OutputSuccess
Important Notes

If you use nextInt() and then nextLine(), you may need to add an extra scanner.nextLine() to consume the leftover newline.

Scanner can read different types like nextDouble(), nextBoolean(), etc.

Summary

The Scanner class reads user input easily.

Use different methods like nextLine() or nextInt() depending on the input type.

Always close the Scanner when done to avoid resource leaks.