繁体   English   中英

读入文本文件传递给Java对象数组

[英]Read in text file pass to an array of objects Java

我正在创建一个像Mint这样的程序。

现在,我正在从文本文件中获取信息,将其按空格分割,然后将其传递给另一个类的构造方法以创建对象。 我在正确完成该设置时遇到了一些麻烦。

我不知道如何从文本文件中获取我真正需要的信息以及其中的所有其他内容。

我需要具有100个斑点的对象数组。 构造函数是

public Expense (int cN, String desc, SimpleDateFormat dt, double amt, boolean repeat)

该文件为:

(0,"Cell Phone Plan", new SimpleDateFormat("08/15/2015"), 85.22, true);
(0,"Car Insurance", new SimpleDateFormat("08/05/2015"), 45.22, true);
(0,"Office Depot - filing cabinet", new SimpleDateFormat("08/31/2015"), 185.22, false);
(0,"Gateway - oil change", new SimpleDateFormat("08/29/2015"), 35.42, false);

下面是我的主要代码:

Expense expense[]  = new Expense[100];
    Expense e = new Expense();
    int catNum;
    String name;
    SimpleDateFormat date = new SimpleDateFormat("01/01/2015");
    double price;
    boolean monthly; 

    try {
        File file = new File("expenses.txt");
        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {                
            String line = scanner.nextLine();
            String array[] = line.split(",");

            expenses[i] = new Expense(catNum, name, date, price, monthly);


        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

一步步:

//(0,"Cell Phone Plan", new SimpleDateFormat("08/15/2015"), 85.22, true);
String array[] = line.split(",");

将产生这个数组

[0] (0
[1] "Cell Phone Plan"
[2] new SimpleDateFormat("08/15/2015")
[3] 85.22
[4] true);

所以

expenses[i] = new Expense(catNum, name, date, price, monthly);

无法工作,因为它期望几乎每个参数中都有另一个数据:

为了解决这个问题:

  • 您必须忽略(); 分割线时
  • 在给定的字符串中注意" ,您必须对这些字符进行换码或忽略它们
  • 您将无法使用: new SimpleDateFormat("08/15/2015")您必须自行创建对象
  • 这不是正确的日期格式“ 08/15/2015”!

解决方案: 如果要创建要解析的文件 ,我建议将其格式更改为:

//(0,"Cell Phone Plan", new SimpleDateFormat("08/15/2015"), 85.22, true);
0,Cell Phone Plan,MM/dd/yyyy,85.22,true

然后:

String array[] = line.split(",");

会产生

[0] 0
[1] Cell Phone Plan
[2] MM/dd/yyyy
[3] 85.22
[4] true

然后,您可以使用以下命令简单地解析非字符串值:


更新

在此处查看一个工作演示,您必须对其进行调整才能使其工作

输出:

public Expense (0, Cell Phone Plan, 08/15/2015, 85.22, false  );
public Expense (0, Car Insurance, 08/05/2015, 45.22, false  );

暂无
暂无

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

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