scanner在java中用法
时间: 2023-09-13 08:08:22 浏览: 94
在Java中使用Scanner需要先导入java.util.Scanner类,然后通过创建Scanner对象来实现输入操作。具体步骤如下:
1. 导入Scanner类
```java
import java.util.Scanner;
```
2. 创建Scanner对象
```java
Scanner scanner = new Scanner(System.in);
```
3. 读取输入值
```java
int num = scanner.nextInt(); // 读取整数
double d = scanner.nextDouble(); // 读取浮点数
String str = scanner.next(); // 读取字符串
```
4. 关闭Scanner对象
```java
scanner.close();
```
完整示例代码:
```java
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入整数:");
int num = scanner.nextInt();
System.out.println("输入的整数为:" + num);
System.out.print("请输入浮点数:");
double d = scanner.nextDouble();
System.out.println("输入的浮点数为:" + d);
System.out.print("请输入字符串:");
String str = scanner.next();
System.out.println("输入的字符串为:" + str);
scanner.close();
}
}
```
阅读全文