In Java, the Scanner class is used to read input from an input source. Usage steps: Create Scanner object: new Scanner (input source) Read input: nextInt(), nextLine() and other methods Close Scanner object: close()
How to use the Scanner class in Java
Introduction:
In Java, the Scanner class is used to retrieve data from various input sources (such as console, file etc.) to read user input.
Syntax:
<code class="java">Scanner scanner = new Scanner(InputStream source);</code>
Among them, source
is an InputStream
object representing the input source.
Usage:
new Scanner()
constructor to create Scanner object. Pass the input source as a parameter to the constructor. nextInt()
, nextLine()
and other methods to read specific types of data. These methods read a value from the input source and convert it to the appropriate type. close()
method to close the Scanner object to release system resources. Example:
<code class="java">import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("输入您的年龄:"); int age = scanner.nextInt(); System.out.println("输入您的姓名:"); String name = scanner.nextLine(); System.out.println("您的年龄是:" + age); System.out.println("您的姓名是:" + name); scanner.close(); } }</code>
Note:
NoSuchElementException
exception will occur. nextLine()
method, it reads the entire line including the newline character. The above is the detailed content of How to use scanner in java. For more information, please follow other related articles on the PHP Chinese website!