The Scanner class is used to read input from users or files. It provides methods for reading different data types: Import Scanner package: import java.util.Scanner Create Scanner object: Scanner(InputStream) from the input stream Read, Scanner(File) reads input from the file: next() reads words, nextInt() reads integers, nextDouble() reads floating point numbers, nextLine() reads a line of text Close Scanner: close() Method to release resources and prevent resource leaks
The Scanner class is used to Input data is read from user input or file, and it provides a convenient interface to handle different data types.
Create a Scanner object: Create a Scanner object using one of the following constructors:
Read input: Use the following methods to read different types of data:
<code class="java">import java.util.Scanner; public class Main { public static void main(String[] args) { // 从控制台读取输入 Scanner scanner = new Scanner(System.in); // 读取姓名 System.out.print("请输入您的姓名:"); String name = scanner.nextLine(); // 读取年龄 System.out.print("请输入您的年龄:"); int age = scanner.nextInt(); // 读取身高 System.out.print("请输入您的身高(单位:厘米):"); double height = scanner.nextDouble(); // 输出结果 System.out.println("姓名:" + name); System.out.println("年龄:" + age); System.out.println("身高:" + height); // 关闭 Scanner scanner.close(); } }</code>
The above is the detailed content of How to use the scanner class in java. For more information, please follow other related articles on the PHP Chinese website!