我正在创建一个像 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);
不会工作,因为它几乎每个参数都需要另一个数据:
为了解决这个问题:
- 分割线时必须忽略
(
and);
- 注意给定字符串中的
"
,你必须将这些字符转义或忽略它们 - 您将无法使用:
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
然后你可以简单地解析非字符串值:
新的 SimpleDateFormat(array[2])
。-
Double.parseDouble(array[3])
-
Boolean.parseBoolean(array[4])
更新
Check here a working demo that you must adapt to make it work .
输出:
public Expense (0, Cell Phone Plan, 08/15/2015, 85.22, false );
public Expense (0, Car Insurance, 08/05/2015, 45.22, false );
关于java - 读入文本文件传递给对象数组 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32825913/