Skip to main content
Published on

Scanner Class in Java

Share:

Introduction

In the world of programming, we frequently encounter situations where interaction with the user is necessary. In Java, the Scanner class emerges as an elegant and effective solution for that purpose.

A Detailed Look at the Scanner Class

The Scanner class, part of the java.util package, is a flexible tool that facilitates reading information from various sources, including user data input, files, and others.

The nextLine() Method and Its Popularity

The nextLine() reads a line of text provided by the user. The great advantage of this method is that it reads text until it finds a line break (usually when the user presses Enter), making it ideal for capturing strings that contain spaces.

Illustrating the Use of the Scanner Class

Let's deepen our use of the Scanner class with a practical example:

package com.caffeinealgorithm.programaremjava;

import java.util.Scanner;

public class ScannerClass {
  public void Run() {
    Scanner userInput = new Scanner(System.in);
    String firstName, lastName;
    int age;

    System.out.print("Enter your first name: ");
    firstName = userInput.nextLine();

    System.out.print("Enter your last name: ");
    lastName = userInput.nextLine();

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

    System.out.printf("Name: %s %s\nAge: %d", firstName, lastName, age);
  }
}

Variety of Scanner Class Methods

The Scanner class is not limited to reading only strings or integers. Let's look at some additional methods:

  • nextInt(): Reads an integer.
  • nextDouble(): Reads a decimal number.
  • nextBoolean(): Reads a boolean value (true or false).
  • next(): Reads a word (until it finds a space).

Beyond User Input

In addition to collecting data from the user, the Scanner class is widely used to read data from files, making it a valuable tool for processing information stored in text files.

Conclusion

The Scanner class in Java is a powerful instrument that, when used correctly, can significantly enhance the interactivity of your applications. Whether capturing user details or reading data from a file, this class is, without a doubt, a valuable addition to your programming repertoire.

Happy coding!