[英]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")
您必须自行创建对象 解决方案: 如果要创建要解析的文件 ,我建议将其格式更改为:
//(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
然后,您可以使用以下命令简单地解析非字符串值:
new SimpleDateFormat(array[2])
。 Double.parseDouble(array[3])
Boolean.parseBoolean(array[4])
输出:
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.