0

该方法使用扫描仪读取第一类和第二类的数据,然后将它们存储在拖车类的 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);
            }
        }
    }
}
4

1 回答 1

1

好的,您可能认为它冗长,但这可能是我在您的限制下会这样做的方式。

public void readFile(String filePath) throws FileNotFoundException {

    final Pattern pattern = Pattern.compile("\n[ ]*,");
    final Scanner fileInput = new Scanner(new File(filePath));

    while (fileInput.hasNextLine()) {
        final String line = fileInput.nextLine().trim();
        final Matcher matcher = pattern.matcher(line);
        final StringBuilder builder = new StringBuilder();
        
        byte flag = 0;
        while (matcher.find()) {
            final String match = matcher.group();
            if(match.startsWith("FirstData")){ flag = 1;}
            else if(match.startsWith("SecondData")){flag = 2;}
            builder.append(line).append(",");
        }
        
        Main mainObj = (flag == 1) ? (new First()) : (flag == 2) ? (new Second()) : null;
        if(null != mainObj){
            mainObj.readData(builder.toString());
        }
    }
}

上面的方法确实要求您在参数中接受 String 而不是 Scanner,但是传递给每个方法的 CSV 格式让每个类的行为处理工作。

于 2013-03-20T19:37:02.143 回答