The Scanner class is used to read input data from the input stream. Its usage is as follows: Create a Scanner object. Use the Scanner method to read different types of data. Process the input data. Close the Scanner object.
The Scanner class is a class in Java that is used to read raw input from an input stream (such as the keyboard, a file, or a network connection) .
1. Create a Scanner object
<code class="java">Scanner scanner = new Scanner(InputStream);</code>
whereInputStream
can beSystem.in
(for reading from the keyboard), file, or network connection.
2. Read input
You can use various methods provided by the Scanner object to read different types of data from the input stream:
nextInt()
:Read the next integernextDouble()
:Read the next double Precision floating point numbernextLine()
:Read a line of texthasNext()
:Check if more input is available3. Process input
After reading the input, you can use Java conditional statements or loops to process the input .
4. Close the Scanner object
After using the Scanner object, you should close it to release resources:
<code class="java">scanner.close();</code>
<code class="java">// 从键盘读取一行文本 Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); // 从文件中读取整数 File file = new File("numbers.txt"); Scanner fileScanner = new Scanner(file); int number = fileScanner.nextInt(); // 从网络连接读取双精度浮点数 URL url = new URL("http://example.com/data.txt"); Scanner networkScanner = new Scanner(url.openStream()); double value = networkScanner.nextDouble(); // 关闭 Scanner 对象 scanner.close(); fileScanner.close(); networkScanner.close();</code>
The above is the detailed content of How to use sanner in java. For more information, please follow other related articles on the PHP Chinese website!