Scanner扫描输入解析数据

wen java案例 4

本文目录导读:

Scanner扫描输入解析数据

  1. 基本使用方法
  2. 数据解析示例
  3. 高级技巧
  4. 注意事项

我来解释一下Java中使用Scanner进行输入数据解析的方法和技巧。

基本使用方法

创建Scanner对象

// 从标准输入读取
Scanner scanner = new Scanner(System.in);
// 从字符串读取
Scanner scanner = new Scanner("Hello World 123");
// 从文件读取
Scanner scanner = new Scanner(new File("data.txt"));

常用输入方法

Scanner scanner = new Scanner(System.in);
// 读取不同类型的数据
String name = scanner.next();        // 读取字符串(遇到空格停止)
String line = scanner.nextLine();    // 读取整行
int number = scanner.nextInt();      // 读取整数
double decimal = scanner.nextDouble(); // 读取小数
long bigNumber = scanner.nextLong();  // 读取长整数
boolean flag = scanner.nextBoolean(); // 读取布尔值

数据解析示例

示例1:解析用户输入的个人信息

public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入姓名、年龄和分数(用空格分隔):");
        String name = scanner.next();
        int age = scanner.nextInt();
        double score = scanner.nextDouble();
        System.out.printf("姓名:%s,年龄:%d,分数:%.1f%n", name, age, score);
        scanner.close();
    }
}

示例2:解析结构化的字符串数据

public class parseData {
    public static void main(String[] args) {
        String data = "张三,25,85.5;李四,30,92.0;王五,28,78.5";
        Scanner scanner = new Scanner(data);
        scanner.useDelimiter("[;,]"); // 设置分隔符为分号或逗号
        List<Student> students = new ArrayList<>();
        while (scanner.hasNext()) {
            String name = scanner.next();
            int age = scanner.nextInt();
            double score = scanner.nextDouble();
            students.add(new Student(name, age, score));
        }
        System.out.println("解析完成:" + students);
        scanner.close();
    }
}
class Student {
    String name;
    int age;
    double score;
    Student(String name, int age, double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
    @Override
    public String toString() {
        return String.format("Student{name='%s', age=%d, score=%.1f}", name, age, score);
    }
}

示例3:从文件解析配置数据

public class FileParser {
    public static void main(String[] args) throws FileNotFoundException {
        // 假设config.txt内容:
        // #这是注释
        // server=localhost
        // port=8080
        // debug=true
        Scanner scanner = new Scanner(new File("config.txt"));
        Properties props = new Properties();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            // 跳过空行和注释
            if (line.isEmpty() || line.startsWith("#")) {
                continue;
            }
            // 解析键值对
            String[] parts = line.split("=");
            if (parts.length == 2) {
                props.setProperty(parts[0].trim(), parts[1].trim());
            }
        }
        System.out.println("配置信息:");
        System.out.println("服务器:" + props.getProperty("server"));
        System.out.println("端口:" + props.getProperty("port"));
        System.out.println("调试模式:" + props.getProperty("debug"));
        scanner.close();
    }
}

高级技巧

使用正则表达式匹配

Scanner scanner = new Scanner(System.in);
// 只匹配数字
scanner.useDelimiter("[^\\d]+");
int phoneNumber = scanner.nextInt();

处理输入验证

public static int readValidInt(Scanner scanner) {
    while (!scanner.hasNextInt()) {
        System.out.println("请输入有效的整数:");
        scanner.next(); // 丢弃无效输入
    }
    return scanner.nextInt();
}

解析复杂格式的日期

String dateStr = "2023-01-15";
Scanner scanner = new Scanner(dateStr);
scanner.useDelimiter("-");
int year = scanner.nextInt();
int month = scanner.nextInt();
int day = scanner.nextInt();
System.out.printf("年:%d,月:%d,日:%d%n", year, month, day);

注意事项

  1. 资源管理:使用完Scanner后要调用close()方法
  2. 输入验证:使用hasNextXxx()方法检查是否有有效输入
  3. 分隔符设置:使用useDelimiter()自定义分隔符
  4. 异常处理:处理InputMismatchException等异常

这样可以灵活地解析各种格式的输入数据,根据具体需求选择合适的解析方式即可。

抱歉,评论功能暂时关闭!