繁体   English   中英

如何从文件中读取数据以创建对象?

[英]How to read data from file to create objects?

我正在努力弄清楚如何从我们得到的文件中读取数据并使用它来创建对象的实例。 我们得到了一个商店客户数据的 txt 文件。 格式如下:123.64382392 12 1.1234123419

文件的每一行都是这样的。 第一列是到货时间,第二列是商品数量,第三列是客户找到一件商品所需的时间。 此文件中有大约 100 个客户,我不确定如何从文件中读取以创建所有必需的实例。

 public static void loadCustomers(){ File file = new File("origCustomerArrivals.txt"); try{ Scanner input = new Scanner(file); while (input.hasNextLine()) { double arrivalTime = input.nextDouble(); int numItems = input.nextInt(); double selectionTime= input.nextDouble(); Customer newCustomer = new Customer(arrivalTime, numItems,selectionTime); input.nextLine(); } input.close(); } catch(FileNotFoundException e){ System.out.println("file not opened"); } } }

尝试这个:

public static void loadCustomers(){
    File file = new File("origCustomerArrivals.txt");
    try{
    List<Customer> list = new ArrayList<Customer>();
    Scanner input = new Scanner(file);
    while (input.hasNextLine())
    {
        String[] values = scan.nextLine().split("\\s+"); 
        arrivalTime = Double.parseDouble(values[0]);
        numItems = Integer.parseInt(values[1]); 
        selectionTime = Double.parseDouble(values[2]);

        Customer newCustomer = new Customer(arrivalTime, numItems,selectionTime);
        list.add(newCustomer);
        input.nextLine();
    }
    input.close();
    }

    catch(FileNotFoundException e){
        System.out.println("file not opened");
    }
}

}

你能详细说明你的代码的哪一部分不起作用吗? 我自己测试了它(打印出值而不是创建一个新的 Customer 对象),它工作正常。 除了“input.nextLine();” 在 while 循环中是没有必要的。 它已经跳到下一行,一旦到达文件末尾,可能会导致抛出错误。

此外,一旦您创建了对象实例,我假设您希望将其保存到对象列表中。 您可以通过在循环外创建对象 Customer 的 ArrayList 来做到这一点:

ArrayList<Customer> Customers = new ArrayList<Customer>();

然后在循环中创建每个实例时,将其添加到此 ArrayList 中:

Customers.add(newCustomer);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM