new Scanner
时间: 2023-09-08 15:10:27 浏览: 50
The `Scanner` class in Java is used for reading input from various sources, such as the console, files, or streams. It provides various methods for reading different data types, such as `nextInt()` for reading integers, `nextDouble()` for reading double values, and `nextLine()` for reading strings.
To create a new `Scanner` object, you can use one of the following constructors:
1. `Scanner(System.in)` - creates a new `Scanner` object to read input from the console.
2. `Scanner(File)` - creates a new `Scanner` object to read input from a file.
3. `Scanner(InputStream)` - creates a new `Scanner` object to read input from an input stream.
For example, to create a new `Scanner` object to read input from the console, you can use the following code:
```
Scanner scanner = new Scanner(System.in);
```
Then, you can use various methods of the `Scanner` class to read input from the console. For example, to read an integer, you can use the `nextInt()` method:
```
int num = scanner.nextInt();
```
Similarly, to read a string, you can use the `nextLine()` method:
```
String str = scanner.nextLine();
```