逐行读取文件,同时将对象存储在每一行的数组中 [英] Reading a file line by line while storing an object in an array for each line

查看:98
本文介绍了逐行读取文件,同时将对象存储在每一行的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,最多可读取4行.每行包含由制表符隔开的字符串和整数的混合.

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.

我已成功使程序读取1行并将所有信息存储在适当的位置,同时还在数组中存储了新对象.

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.");
        }
}

和readRecord()方法:

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();
}

推荐答案

最后解决了我的问题!

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;
}

这篇关于逐行读取文件,同时将对象存储在每一行的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆