该方法使用扫描仪读取第一类和第二类的数据,然后将它们存储在拖车类的 ArrayList 中。First 和 Second 继承自 Main Class。我遇到的问题是我创建的对象的重复。
我怎样才能只创建一个并将其用于两者。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Auto {
private ArrayList<Main> lists;
public Auto() {
lists = new ArrayList<Main>();
}
public void storeData(Main main) {
list.add(main);
}
public void readFile(String filePath) throws FileNotFoundException {
File file = new File(filePath);
Scanner input = new Scanner(file);
String dataToBe;
while (input.hasNext()) {
String lines = input.nextLine().trim();
Scanner scanner = new Scanner(lines).useDelimiter("\n[ ]*,");
if (lines.startsWith("Data")) {
if (lines.startsWith("FirstData")) {
dataToBe = "first";
} else if (lines.startsWith("SecondData")) {
dataToBe = "second";
}
} else if (dataToBe.equals("first")) {
Main main = new First();
main.readData(scanner);
storeData(main);
} else if (dataToBe.equals("second")) {
Main main = new Second();
main.readData(scanner);
storeData(main);
}
}
}
}