在令牌化后,如何将来自该构造函数的具有两种数据类型的数据存储到数组中?

时间:2019-03-15 01:21:37

标签: java arrays storage stringtokenizer

我在这里有这个构造函数类

public class Car {
private String make,model;
private int year,mileage;

public String toString() {
return "Car [make=" + make + ", model=" + model +", "
        + "year =" + year + ", mileage=" + mileage + "]"; }


public String getMake() {
    return make;
}
public Car(String make, String model, int year, int mileage) {
    super();
    this.make = make;
    this.model = model;
    this.year = year;
    this.mileage = mileage;
}
public void setMake(String make) {
    this.make = make;
}
public String getModel() {
    return model;
}
public void setModel(String model) {
    this.model = model;
}
public int getYear() {
    return year;
}
public void setYear(int year) {
    this.year = year;
}
public int getMileage() {
    return mileage;
}
public void setMileage(int mileage) {
    this.mileage = mileage;
}
}

现在使用这种方法,我试图将数据存储到两个数组中,其中一个将使用排序算法进行排序,但是我在理解如何将它们存储在不同类型的数组中时遇到了麻烦。我尝试自己尝试,但我认为这样做不正确。它应该从文本文件中读取并存储品牌,型号年份和里程,但事实是这是两种数据类型,这让我很吃惊。

import java.util.ArrayList;
import java.util.StringTokenizer;

public class Storing {

public static void main(String[] args) {

    TextFileInput fileInput = new TextFileInput("CarDetails.txt");
    ArrayList <Car> cars = new ArrayList<Car>();
    String line = fileInput.readLine();


    while(line!=null) {
        int [] values = new int [4];

        StringTokenizer st = new StringTokenizer(line,",");
        int numOfCommas = st.countTokens();

        for(int i = 0;i<numOfCommas;i++) {
            values[i]=Integer.parseInt(st.nextToken(","));
        }
        cars.add(new Car(values[0],values[1],values[2],values[3]));

        line = fileInput.readLine();
    }

请帮助我朝正确的方向前进。

2 个答案:

答案 0 :(得分:0)

makemodel不是int。只需读入String[]并仅解析最后两个标记。像

while (line != null) {
    String[] values = new String[4];

    StringTokenizer st = new StringTokenizer(line, ",");
    int numOfCommas = st.countTokens();

    for (int i = 0; i < numOfCommas; i++) {
        values[i] = st.nextToken();
    }
    cars.add(new Car(values[0], values[1], 
            Integer.parseInt(values[2]), Integer.parseInt(values[3])));

    line = fileInput.readLine();
}

答案 1 :(得分:0)

您可以将其解析为其他数据类型,然后将其解析。泛型将一次只允许一种数据类型,但不能同时允许两种不同的数据类型...