Reputation: 151
I am creating a program like Mint.
right now, I am getting information from a text file, splitting it by the spaces, then going to pass it to the Constructor of another class to create objects. I am having a bit of trouble getting that done properly.
I don't know how to get the information I actually need from the text file with all the extra stuff that's in it.
I need to have an array of objects that has 100 spots. The Constructor is
public Expense (int cN, String desc, SimpleDateFormat dt, double amt, boolean repeat)
The file comes as :
(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);
Below is my code for the main:
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();
}
Upvotes: 1
Views: 1164
Reputation: 26961
Step by step:
//(0,"Cell Phone Plan", new SimpleDateFormat("08/15/2015"), 85.22, true);
String array[] = line.split(",");
Will produce this array
[0] (0
[1] "Cell Phone Plan"
[2] new SimpleDateFormat("08/15/2015")
[3] 85.22
[4] true);
So
expenses[i] = new Expense(catNum, name, date, price, monthly);
Wont work because it expects another data in almost each parameter:
In order to fix this:
(
and );
when splitting line"
in the given string, you must scape this characters or ignore themnew SimpleDateFormat("08/15/2015")
you must create the object by yourselfSOLUTION: if you are creating the file to parse, I would recommend to change it's format to:
//(0,"Cell Phone Plan", new SimpleDateFormat("08/15/2015"), 85.22, true);
0,Cell Phone Plan,MM/dd/yyyy,85.22,true
Then:
String array[] = line.split(",");
Will produce
[0] 0
[1] Cell Phone Plan
[2] MM/dd/yyyy
[3] 85.22
[4] true
Then you can simply parse non string values with:
new SimpleDateFormat(array[2])
.Double.parseDouble(array[3])
Boolean.parseBoolean(array[4])
Check here a working demo that you must adapt to make it work.
OUTPUT:
public Expense (0, Cell Phone Plan, 08/15/2015, 85.22, false );
public Expense (0, Car Insurance, 08/05/2015, 45.22, false );
Upvotes: 3