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
Release: 2024-11-09 14:23:02
Original
1003 people have browsed it

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;
Copy after login
  1. Create a Scanner object: Instantiate a Scanner object, passing in the standard input stream as an argument.
Scanner in = new Scanner(System.in);
Copy after login
  1. Read integer value: Use the nextInt() method to read an integer value from the standard input buffer.
int num = in.nextInt();
Copy after login

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);
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template