首页 > 解决方案 > 如何传递读取的 .text 文件并使其成为对象

问题描述

汽车

汽车数据集在文件 (cars_input1.txt) 中提供。

该文件包含每辆车的三个字段:

 Name, Origin, Horsepower. 

给定这个文件并给定一个数字 N 和一个原点 O,打印 N 辆马力大于原点 O 的所有汽车的平均马力的汽车。

请注意,应根据给定来源的汽车而不是整个数据集计算平均马力。

数据集的路径以及 N 和 O 的值将作为参数传递给命令行上的程序。

例如,在下面的数据集中:

Chevrolet Chevelle Malibu,130.0,US
Buick Skylark 320,165.0,US
Plymouth Satellite,150.0,US
Volkswagen 1131 Deluxe Sedan,46.0,Europe
Peugeot 504,87.0,Europe
Audi 100 LS,90.0,Europe

给定 N=1 和 O=US,输出应该是:

Buick Skylark 320,165.0,US

给定 N=2 和 O=US,输出应该是:

Buick Skylark 320,165.0,US
Plymouth Satellite,150.0,US

给定 N=3 和 O=US,输出应该是:

Buick Skylark 320,165.0,US
Plymouth Satellite,150.0,US

同样,给定 N=1 和 O=Europe,输出应该是:

 Audi 100 LS,90.0,Europe

给定 N=2 和 O=Europe,输出应该是:

 Peugeot 504,87.0,Europe
Audi 100 LS,90.0,Europe

给定 N=3 和 O=Europe,输出应该是:

Peugeot 504,87.0,Europe
Audi 100 LS,90.0,Europe

我试过这样的东西

public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("Car.txt"));
    input.useDelimiter(",|\n");
    Product[] products = new Product[0];
    while(input.hasNext()) {
        String name = input.next();
        String origin = input.next();
        String horsepower = input.next();
        Product newProduct = new Product(name,origin,horsepower);
}
public static class Product {
    protected String name;
    protected String origin;
    protected String horsepower;
    public Product(String n, String p, String d) {
        name = n;
        origin = p;
        horsepower = d;
    }

我没有得到想要的输出

标签: java

解决方案


除非您可以绝对确定该文件是有效的,否则您永远不应该以您的方式拆分逗号分隔的值文件。而是使用正则表达式:

public static final Pattern LINE_PATTERN = Pattern.compile("([^\\,]+)\\,([^\\,]+)\\,([^\\,]+)");
...

Matcher lineMatcher = LINE_PATTERN.matcher(line);
if (matcher.matches()) {
  String name = matcher.group(1);
  String origin = matcher.group(2);
  String horsepower = matcher.group(3);
  // do something with the values (for example put them into an array)
} else {
  // print some error
}

这可能会更强大,并为您提供过滤格式错误的行和打印错误的选项。(这不会过滤前导或尾随空格。如果需要,您可以在获得结果后对结果进行 .trim() 或相应地更改表达式)

public static final Pattern LINE_PATTERN = Pattern.compile("\\s*([^\\,\\s]+)\\s*\\,\\s*([^\\,\\s]+)\\s*\\,\\s*([^\\,\\s]+)\\s*");

推荐阅读