Home >Java >javaTutorial >How to Read Integer Values from Standard Input in Java?

How to Read Integer Values from Standard Input in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-09 14:23:021021browse

How to Read Integer Values from Standard Input in Java?

Reading Integer Values from Standard Input in Java

In Java, there are several classes that can be used for reading input from the standard input stream. However, the most commonly used class for this task is java.util.Scanner.

Using java.util.Scanner

To read an integer value from the standard input using Scanner, follow these steps:

  1. Import the Scanner class: Add the following line to the beginning of your Java program:
import java.util.Scanner;
  1. Create a Scanner object: Instantiate a Scanner object, passing in the standard input stream as an argument.
Scanner in = new Scanner(System.in);
  1. Read integer value: Use the nextInt() method to read an integer value from the standard input buffer.
int num = in.nextInt();

Example

Here's an example of how to use Scanner to read an integer value from the standard input:

import java.util.Scanner;

public class Example {

    public static void main(String[] args) {
        // Create a Scanner object
        Scanner in = new Scanner(System.in);

        // Read an integer value
        int num = in.nextInt();

        // Print the integer value
        System.out.println(num);
    }
}

This code reads an integer value from the standard input and prints it to the console.

The above is the detailed content of How to Read Integer Values from Standard Input in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn