In Java, How Can I Use The Scanner Class To Read Input From The Console?

To read input from the console using the Scanner class in Java, you can follow these steps:

  1. First, you need to import the Scanner class by adding the following line at the beginning of your code:
import java.util.Scanner;
  1. Next, create an instance of the Scanner class by using the following code:
Scanner scanner = new Scanner(System.in);

Here, scanner is the object that you will use to read input from the console.

  1. To read input from the console, you can use various methods provided by the Scanner class. Some commonly used methods are:
  • nextLine(): Reads a complete line of input as a String.
  • nextInt(): Reads the next token of input as an integer.
  • nextDouble(): Reads the next token of input as a double.

For example, to read a line of input from the console, you can use the following code:

String inputLine = scanner.nextLine();
  1. After you finish reading input from the console, it is good practice to close the Scanner object using the close() method:
scanner.close();

Here’s an example code that demonstrates how to read input from the console using the Scanner class:

import java.util.Scanner;

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

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        System.out.println("Hello, " + name + "!");

        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        System.out.println("You are " + age + " years old.");

        scanner.close();
    }
}

In this example, the program prompts the user to enter their name and age. It then reads the input using the nextLine() and nextInt() methods of the Scanner class and displays the entered values.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!