Java 输入数据用法

Scanner 类
最常用、最易懂,适合输入整数、小数、字符串等各种类型数据。

  1. 使用步骤
    导入包:import java.util.Scanner;
    创建 Scanner 对象
    调用方法读取数据
  2. 完整代码示例
  3. // 1. 导入Scanner包
    import java.util.Scanner;

public class InputDemo {
public static void main(String[] args) {
// 2. 创建Scanner对象
Scanner sc = new Scanner(System.in);

// 3. 输入整数
System.out.print("请输入一个整数:");
int num = sc.nextInt();

// 输入小数
System.out.print("请输入一个小数:");
double dou = sc.nextDouble();

// 输入字符串(不带空格)
System.out.print("请输入一个单词:");
String str = sc.next();

// 输入带空格的字符串
System.out.print("请输入一句话:");
sc.nextLine(); // 吸收换行符
String line = sc.nextLine();

// 输出结果
System.out.println("你输入的整数:" + num);
System.out.println("你输入的小数:" + dou);
System.out.println("你输入的单词:" + str);
System.out.println("你输入的句子:" + line);

// 关闭扫描器
sc.close();
}
}

  1. Scanner 常用方法
    | 方法 | 作用 |
    | ------------- | ------------------ |
    | nextInt() | 读取整数 |
    | nextDouble() | 读取小数 |
    | next() | 读取字符串(遇到空格 / 回车停止) |
    | nextLine() | 读取整行字符串(包含空格) |
    | nextBoolean() | 读取布尔值 |
  2. Scanner 常用方法
  3. | 方法 | 作用 |
    | ------------- | ------------------ |
    | nextInt() | 读取整数 |
    | nextDouble() | 读取小数 |
    | next() | 读取字符串(遇到空格 / 回车停止) |
    | nextLine() | 读取整行字符串(包含空格) |
    | nextBoolean() | 读取布尔值 |
posted @ 2026-05-13 15:05  我不想喝清水  阅读(14)  评论(0)    收藏  举报