Java编程项目

问题描述 投票:-1回答:1

我正处于大学项目的中间,任务是使用扫描仪读取几个数据文件中的适当数据。该项目涉及一个超类和几个子类。到目前为止,以下方法可以正常工作,并读取与名为Tool的类及其所有字段相对应的数据。但是,我最近添加了一个子类ElectricTool,该子类扩展了类Tool,并且引入了两个新字段,它们需要以与以前相同的方式但在下面所示的相同方法中读取。我已经尝试了许多方法,但是似乎无法弄清楚。有什么建议么?最好尽可能使用干净/简单的代码,我认为这需要是一条读取语句,但我一直在努力。方法如下:

public void readToolData()

{
    Frame myFrame = null;
    FileDialog fileBox = new FileDialog(myFrame,"Open", FileDialog.LOAD);
    fileBox.setVisible(true);
    String directoryPath = fileBox.getDirectory();
    String fileName = fileBox.getFile();

    File dataFile = new File(fileName);
    System.out.println(fileName +"  "+ directoryPath);
    Scanner scanner = null;
    try
    {
        scanner = new Scanner(dataFile);
    }
    catch (FileNotFoundException e)
    {
        System.out.println(e);
    }

    while( scanner.hasNextLine() )
    {
        String lineOfText = scanner.nextLine().trim().replaceAll("\\s+","");
        if(!lineOfText.isEmpty() && !lineOfText.matches("^//.*") && !lineOfText.substring(0,1).equals("["))
        {
            System.out.println(lineOfText);      
        }
        else{
            continue;
        }

        Scanner scanner2 = new Scanner(lineOfText).useDelimiter("\\s*,\\s*");
        while(scanner2.hasNext())
        {
            Tool tool = new Tool();
            tool.readData(scanner2);


            storeToolList(tool);
        }

    }
    scanner.close();
}

electric tool class

tool class

data file

java subclass
1个回答
0
投票
        Scanner scanner2 = new Scanner(lineOfText).useDelimiter("\\s*,\\s*");
        while(scanner2.hasNext())
        {
            ElectricTool tool = new ElectricTool();
            tool.readData(scanner2);


            storeToolList(tool);
        }

和在ElectricTool类中:

public class ElectricTool extends Tool {

 @Override
 public void readData(Scanner scanner) {
    // Here you read the data from scanner and set the fields of the electric tool
 }
© www.soinside.com 2019 - 2024. All rights reserved.