如何传递读取的.text文件并使其成为对象

时间:2018-09-03 12:03:58

标签: java

汽车

文件(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 =欧洲,输出应为:

 Audi 100 LS,90.0,Europe

鉴于N = 2和O = Europe,输出应为:

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

鉴于N = 3,O =欧洲,输出应为:

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;
    }

我没有得到想要的输出

2 个答案:

答案 0 :(得分:0)

除非绝对可以确定文件有效,否则切勿以逗号分割值文件。而是使用正则表达式:

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*");

答案 1 :(得分:0)

import java.io.BufferedReader;
// Reading data from a file using FileReader 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException;
import java.io.InputStreamReader; 
public class cars {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        // variable declaration 
        int ch,i; 
        int numline=0;
        BufferedReader br = null;
        String arr[][] = new String[100][100];
    String path=args[0];
        /*
         * Part-1: Parsing input file content
         */
        String delimiter = ",";
        try {
            //Reading file -- Provide location of the input file
            br = new BufferedReader(new FileReader(path));             
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();         
            String []tempArray;
            //Reading file line by line and storing it in a 2-D array
            while (line != null) {                                       
                /* given string will be split by the argument delimiter provided. */
                tempArray = line.split(delimiter);
                arr[numline] = tempArray;
                numline++;
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            System.out.println("Input file content:");
            for(i=0;i<numline;i++){
                int j;
                for(j=0;j<2;j++) {
                    System.out.print(arr[i][j]);
                    System.out.print(",");
                }
                System.out.print(arr[i][j]);
                System.out.println();
            }            
        }
        catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }
        finally 
        {
            try 
            {
                br.close();
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }

        /*
         * Part-2: Implementing requirement logic
         */
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int N;
        String O;
    System.out.println("------------------------------");
    System.out.println("Solution of the Above Problem");
    System.out.println("------------------------------");
        N = Integer.parseInt(args[1]); 
        O = args[2];
        double sumHP=0;
        double avgHP=0;
        double hp;
        int originCount = 0;
        //Find average horsepower for origin O
        for(i=0;i<numline;i++)
        {
            if(arr[i][2].equals(O))
            {
                hp = Double.parseDouble(arr[i][1]);
                sumHP += hp;
                originCount++;
            }
        }
        if(N>originCount)
        {
            System.out.println("Value of N is larger than number of details for the given origin");
            System.exit(-1);
        }
        if(originCount>0)        
            avgHP = sumHP/originCount;
        int cnt=0; //counter variable to track how many details have been printed till now
        for(i=0;i<numline;i++)
        {
            hp = Double.parseDouble(arr[i][1]);
            if(hp>avgHP && cnt<N && arr[i][2].equals(O))
            {
                int j;
                for( j=0;j<2;j++)
                {
                    System.out.print(arr[i][j]+",");
                }
                System.out.print(arr[i][j]);
                System.out.println();
                cnt++;
            }
        }        
    }

}

Blockquote