减少继承中的代码重复

时间:2013-03-20 18:39:43

标签: java if-statement inheritance bluej

该方法使用scanner读取First类和第二类的数据,然后将它们存储在两个ArrayList的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);
            }
        }
    }
}

1 个答案:

答案 0 :(得分: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格式允许每个类的行为处理工作。