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

How to Read Integers from Standard Input in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 06:04:02836browse

How to Read Integers from Standard Input in Java?

Reading Integers from Standard Input in Java

Reading integer values from the standard input (console) is a common task in Java programming. To accomplish this, you can utilize the java.util.Scanner class.

Using Scanner

Instantiate a Scanner object using the new keyword and provide System.in as an argument. System.in represents the standard input stream.

import java.util.Scanner;

//...

Scanner in = new Scanner(System.in);

Reading an Integer

To read an integer value from the console, use the nextInt() method:

int num = in.nextInt();

The nextInt() method returns the next integer value found in the console input.

Considerations

  • Closing the Scanner object using in.close() is recommended for resource cleanup.
  • Scanner can also tokenize input using regular expressions and provide other input handling capabilities.
  • Alternatively, you can use low-level methods like BufferedReader and InputStream for more control over input operations, but Scanner provides a convenient and common interface for this task.

The above is the detailed content of How to Read Integers 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