Reading a file line by line while storing an object in an array for each line

那年仲夏 提交于 2020-01-04 07:01:40

问题


I have a text file with a maximum of 4 lines to read from. Each line has a mixture of strings and integers spaced out by tabs.

I have successfully made my program read 1 line and store all the information in the appropriate spot, while also storing a new object in the array.

The problem: I can't figure out how to get it to read multiple lines while also storing a new object in the array depending on the line read.

Here is my method that takes the file and and stores an object in the array:

public void addVehicle(Vehicle Honda[]) throws FileNotFoundException
{
    Scanner reader = new Scanner(file);

        if(canAddVehicle() == true)
        {
        for(int i = 0; i < vehicles.length; i++)
        {
            if(vehicles[i] == null)
            {
                Honda[i] = new Vehicle();
                Honda[i].readRecord(reader);
                vehicles[i] = Honda[i];
                reader.close();
                break;
            }
        }
            System.out.println("Vehicle Added!");
        }
        else
        {
            System.out.println("You can not add more than 4 vehicles.");
        }
}

And the readRecord() method:

public void readRecord(Scanner reader)
{
    while(reader.hasNextLine())
    {
        setMake(reader.next());
        setModel(reader.next());
        setYear(reader.nextInt());
        setvin(reader.next());
        setValue(reader.nextDouble());
        setMilesDriven(reader.nextInt());
        setLastOilChange(reader.nextInt());
    }
    reader.close();
}

回答1:


If you can only successfully store one Vehicle instance, it's because your closing the reader too soon.

In addVehicle(), get rid of

reader.close();

and in readRecord(), get rid of

reader.close();

Close the reader at the end of addVehicle().




回答2:


Finally fixed my problem!

public boolean addVehicle(Vehicle[] Honda) throws FileNotFoundException
{
    boolean found = false;
    int position = 0;
        if(canAddVehicle() == true)
        {
            for(int i = 0; i < vehicles.length && !found; i++)
            {
                if(vehicles[i] == null)
                {
                    position = i;
                    found = true;
                }
            }

               Scanner reader = new Scanner(file);
               while(reader.hasNext())
               {
                   Honda[position] = new Vehicle();
                   Honda[position].readRecord(reader);
                   vehicles[position] = Honda[position];
                   position++;

               }
                reader.close();
                return true;
        }
        return false;
}


来源:https://stackoverflow.com/questions/8410050/reading-a-file-line-by-line-while-storing-an-object-in-an-array-for-each-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!