Read in text file pass to an array of objects Java - java

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();
}

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:
you must ignore ( and ); when splitting line
be careful with " in the given string, you must scape this characters or ignore them
you wont be able to use: new SimpleDateFormat("08/15/2015") you must create the object by yourself
this is not a correct date format "08/15/2015"!!!!
SOLUTION: 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])
UPDATE
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 );

Related

Is there a way loop through 2 arrays and print the element of array 1 if it contains the substring of any element from array 2?

The problem I am trying to solve is how to read lines from a text file and add it to an array. Then sort each element from this new array by the date that is also in each element. I will explain so its easier to understand but will explain what I am doing.
My text file (First column is name, second is Date of birth and last is the date the person died):
sarah jones,1966-12-02,2018-12-04
matt smith,1983-02-03,2020-03-02
john smith,1967-03-04,2017-04-04
I want to sort this file and output it to another file (testing by printing to console at the moment) by sorting it by the date the person died. A way I thought of doing this is to read each line and pass it to an array. Then read each element within the array, split it and then save the date the person died to another array. Then sort the array that has the death dates, loop through both arrays by seeing if the first element of the death date array matches the first element of the first line in the text file, if so then write it to another file. If not then go to the next line.
For example
BufferedReader reader = new BufferedReader(new FileReader("input_text.txt"));
PrintWriter outputStream = new PrintWriter(new FileWriter("output.txt",true));
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> substr_date = new ArrayList<String>();
String currentline = reader.readLine();
while(currentline !=null){
String a_line[] = currentline.split(",");
substr_date.add(a_line[2])
lines.add(currentline);
currentline = reader.readLine();
}
Collections.sort(substr_date);
for(String date : substr_date){
for(String line : lines){
if(line.contains(date)){
System.out.println(line);
}
}
}
I expect the output to be:
john smith,1967-03-04,2017-04-04
sarah jones,1966-12-02,2018-12-04
matt smith,1983-02-03,2020-03-02
The results are initially in order but then some lines are repeated multiple times and then the whole text file in repeated to the console and becomes a mess. I am not sure how to go about doing this. I am new to java and not sure if I asked this question properly either so if you need any more info please ask.
I would create class for objects which you can insert into a list and then define a comparator on this class which you can use to sort.
Here is an example of the class you could define:
static class DeceasedPerson {
String name;
LocalDate birthDate;
LocalDate deathDate;
DeceasedPerson(String name, LocalDate birthDate, LocalDate deathDate) {
this.name = name;
this.birthDate = birthDate;
this.deathDate = deathDate;
}
#Override
public String toString() {
return name + ", " + birthDate + ", " + deathDate;
}
}
Then you could simply load objects based on this class into a list which you sort using a comparator. Here is some sample code you can run with the class defined above:
public static void main(String[] args) {
String input =
"matt smith,1983-02-03,2020-03-02\n" +
"sarah jones,1966-12-02,2018-12-04\n" +
"john smith,1967-03-04,2017-04-04\n";
List<DeceasedPerson> deceasedPersonList = new ArrayList<>();
try (Scanner scanner = new Scanner(input)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] array = line.split(",");
DeceasedPerson deceasedPerson = new DeceasedPerson(array[0],
LocalDate.parse(array[1]), LocalDate.parse(array[2]));
deceasedPersonList.add(deceasedPerson);
}
}
deceasedPersonList.sort(Comparator.comparing(o -> o.deathDate));
deceasedPersonList.forEach(System.out::println);
}
If you run the code above using the DeceasedPerson class you should see on the console the following output:
john smith, 1967-03-04, 2017-04-04
sarah jones, 1966-12-02, 2018-12-04
matt smith, 1983-02-03, 2020-03-02
You could actually also use a TreeSet instead of a List in the main method above and achieve the same results. Here is a move concise alternative:
public static void main(String[] args) {
String input =
"matt smith,1983-02-03,2020-03-02\n" +
"sarah jones,1966-12-02,2018-12-04\n" +
"john smith,1967-03-04,2017-04-04\n";
Set<DeceasedPerson> deceasedPersonList = new TreeSet<>(Comparator.comparing(o -> o.deathDate));
try (Scanner scanner = new Scanner(input)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] array = line.split(",");
DeceasedPerson deceasedPerson = new DeceasedPerson(array[0],
LocalDate.parse(array[1]), LocalDate.parse(array[2]));
deceasedPersonList.add(deceasedPerson);
}
}
deceasedPersonList.forEach(System.out::println);
}
The way you are doing is a long shot. You can do this in much simpler way. You could pass a comparator to the Collections.sort() method like this.
Collections.sort(substr_date, new Comparator<String>{
#Override
public int compare(String str1, String str2){
String dd1 = str1.split(",")[2];
String dd2 = str2.split(",")[2];
return dd1.compareTo(dd2);
}
});
Comparing dates like this, though, is not a good approach. You should convert the date string to LocalDateTime and then use isBefore() or isAfter() to compare them. For ex,
public int compare(String str1, String str2){
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd")
LocalDateTime d1 = LocalDateTime.parse(str1.split(",")[2],format);
LocalDateTime d2 = LocalDateTime.parse(str2.split(",")[2],format);
return d1.isBefore(d2)?-1:(d1.isAfter(d2)?1:0);
}

Modifying complex csv files in java

I wanted to write a program which can print, and modify the irregular csv files. The format is as follows:
1.date
2.organization name
3. student name, id number, residence
student name, id number, residence
student name, id number, residence
student name, id number, residence
student name, id number, residence
1.another date
2.another organization name
3. student name, id number, residence
student name, id number, residence
student name, id number, residence
..........
For instance, the data may be given as follows:
1. 10/09/2016
2. cycling club
3. sam, 1000, oklahoma
henry, 1001, california
bill, 1002, NY
1. 11/15/2016
2. swimming club
3. jane, 9001, georgia
elizabeth, 9002, lousiana
I am a beginner and I have not found any viable resource online which deals with this type of problem. My main concern is, how do we iterate through the loop and identify the date and name of the club, and feed them into a array?
Please advise.
I think this should be helpful for you. Basically there should be some pattern in your messed up csv. Below is my code to arrange your csv
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter("file.txt", "UTF-8");
try{
//Create object of FileReader
FileReader inputFile = new FileReader("csv.txt");
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
//Variable to hold the one line data
String line;
String date="";String org ="";String student ="";
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
if(line.contains("1.")){
if(date!="" || org!=""){
writer.println(date+","+org+","+student);
student ="";
}
date = line.substring(2);
}else if(line.contains("2.")){
org = line.substring(2);
}else{
line = "("+line+")";
student += line+",";
}
System.out.println(line);
}
writer.println(date+","+org+","+student);
//Close the buffer reader
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:" + e.getMessage());
}
writer.close();
}
This is the output you will get for this
10/09/2016, cycling club,(3. sam, 1000, oklahoma),( henry, 1001, california),( bill, 1002, NY),
11/15/2016, swimming club,(3. jane, 9001, georgia),( elizabeth, 9002, lousiana),
I am reading the file from csv.txt. while loop goes through each line of text file.all the fields are stored in a variable. When next date comes I write all of them into output file. Last line of the csv is written to file after the while loop terminates.
Try uniVocity-parsers to handle this. For parsing this sort of format, you'll find a few examples here. For writing, look here and here.
Adapting from the examples I've given, you could write:
final ObjectRowListProcessor dateProcessor = new ObjectRowListProcessor();
final ObjectRowListProcessor clubProcessor = new ObjectRowListProcessor();
final ObjectRowListProcessor memberProcessor = new ObjectRowListProcessor();
InputValueSwitch switch = new InputValueSwitch(0){
public void rowProcessorSwitched(RowProcessor from, RowProcessor to) {
//your custom logic here
if (to == dateProcessor) {
//processing dates.
}
if (to == clubProcessor) {
//processing clubs.
}
if (to == memberProcessor){
//processing members
}
};
switch.addSwitchForValue("1.", dateProcessor, 1); //getting values of column 1 and sending them to `dateProcessor`
switch.addSwitchForValue("2.", clubProcessor, 1); //getting values of column 1 and sending them to `clubProcessor`
switch.addSwitchForValue("3.", memberProcessor, 1, 2, 3); //getting values of columns 1, 2, and 3 and sending them to `memberProcessor`
setDefaultSwitch(memberProcessor, 1, 2, 3); //Rows with blank value at column 0 are members. Also get columns 1, 2, and 3 and send them to `memberProcessor`
CsvParserSettings settings = new CsvParserSettings(); //many options here, check the tutorial and examples
// configure the parser to use the switch
settings.setRowProcessor(switch);
//creates a parser
CsvParser parser = new CsvParser(settings);
//parse everying. Rows will be sent to the RowProcessor of each switch, depending on the value at column 0.
parser.parse(new File("/path/to/file.csv"));
Disclaimer: I'm the author of this library, it's open-source and free (Apache 2.0 license)

Reading txt file, then re organizing it to an array

So basically what I need to do is:
Read a text file like this:
[Student ID], [Student Name], Asg 1, 10, Asg 2, 10, Midterm, 40, Final, 40
01234567, Timture Choi, 99.5, 97, 100.0, 99.0
02345678, Elaine Tam, 89.5, 88.5, 99.0, 100
and present it like this (with calculations of rank and average):
ID Name Asg 1 Asg 2 Midterm Final Overall Rank
01234567 Timture Choi 99.5 97.0 100.0 99.0 99.3 1
02345678
Elaine Tam 89.5 88.5 99.0 100.0 97.4 2
Average: 94.5 92.75 99.5 99.5 98.3
Using printf() function
now this is what I have done so far:
import java.io.*;
import java.util.Scanner;
class AssignmentGrades {
public static void main(String args[]) throws Exception {
Scanner filename = new Scanner(System.in);
String fn = filename.nextLine(); //scannig the file name
System.out.println("Enter your name of file : ");
FileReader fr = new FileReader(fn+".txt");
BufferedReader br = new BufferedReader (fr);
String list;
while((list = br.readLine()) !=null) {
System.out.println(list);
}
fr.close();
}
}
So I can ask the user for the name of the file, then read it and print.
Now.. I'm stuck. I think I need to probably put it in to array and split?
String firstrow = br.readLine();
String[] firstrow = firstrow.split(", ");
something like that?.. ugh ive been stuck here for more than an hour
I really need help!! I appreciate your attention!! ( I started to learn java this week)
There are two ways for splitting the input line just read from the file
Using String object's split() method which would return an array. Read more about the split here.
StringTokenizer Class - This class can be used to divide the input string into separate tokens based on a set of delimeter. Here is a good tutorial to get started.
You should be able to get more examples using google :)
In case you want to parse integers from String. Check this.
Here I store the columns as an array of Strings and I store the record set as an ArrayList of String arrays. In the while loop if the column set is not initialized yet (first iteration) I initialize it with the split. Otherwise I add the split to the ArrayList. Import java.util.ArrayList.
String[] columns = null;
ArrayList<String[]> values = new ArrayList<String[]>();
String list;
while((list = br.readLine()) !=null) {
if (columns != null) {
columns = list.split(", ");
} else {
values.add(list.split(", "));
}
}
fr.close();

Read from txt file not working properly

I'm using this method
static void readFile()
{
try
{
FileInputStream fstream = new FileInputStream( "Insurances.txt" );
BufferedReader br = new BufferedReader( new InputStreamReader( fstream ) );
String strLine;
String [] array;
while ( ( strLine = br.readLine() ) != null )
{
array = strLine.split( "," );
pword++;
int type = Integer.parseInt(array[0]);
int tm = Integer.parseInt(array[1]);
int year = Integer.parseInt(array[2]);
int month = Integer.parseInt(array[3]);
int day = Integer.parseInt(array[4]);
int pass = Integer.parseInt(array[5]);
double tc = 0;
if ( type==2 )
{
String man = array[6];
String mod = array[7];
int cc = Integer.parseInt(array[8]);
String lp = array[9];
String ex = array [10];
boolean extra;
if ( ex.equals("true") )
{
extra = true;
}
else
{
extra = false;
}
insurances[insur] = new CarInsurance( pword, type, tm, year, month, day, pass, tc, man, mod, cc, lp, extra );
tc = insurances[insur].calculateCost( pass, a, insur );
insurances[insur].setCost( tc );
insur++;
}
else
{
insurances[insur] = new LifeInsurance( pword, type, tm, year, month, day, pass, tc );
tc = insurances[insur].calculateCost( pass, a, insur );
insurances[insur].setCost( tc );
insur++;
}
System.out.println("y");
}
inp.close();
}
catch ( Exception e )
{
e.getMessage();
}
}
to read some info from a txt file and create an object of my LifeInsurance class or my CarInsurance. The reason i use this System.out.println("y"); is to see whether it completes as many loops as the objects i want to create. When i try to run my programm i only get 7 loops ( 7 y's ) but i need 13. The following is what i have wrote on the txt file :
1,12,2013,6,1,1939
2,12,2008,1,10,1939,Mercedes,E200,2000,AEX32100,false
2,12,2009,1,11,1939,Mercedes,E200,2000,AEX32100,false
2,12,2009,2,10,1940,Fiat,Punto,1400,BIO1245,false
2,12,2009,2,10,1940,Seat,Ibiza,1600,BIE3987,false
2,12,2010,1,10,1940,Seat,Ibiza,1600,BIE3987,false
2,12,2013,6,1,1941,Audi,A4,1600,IXE1256,true
1,12,2008,1,2,1942
1,12,2009,1,2,1942
1,12,2010,1,2,1942
1,12,2011,1,2,1943
2,12,2010,7,23,1943,Renault,Clio,1400,ZIO3890,true
2,12,2011,7,23,1943,Renault,Clio,1400,ZIO3890,true
Could you please help me out because i can't find a reason why it doesn't complete all 13 loops. Thank you in advance.
You should see the line 18 of your LifeInsurance class as suggests your stacktrace:
java.lang.NullPointerException at LifeInsurance.calculateCost(LifeInsurance.java:18)
The data of your 8th line seems to induce something null in the cost calculation.
In order to know if it is an error from inexpected kind of data or a problem in your code, you should first replace 1st line by your 8th and then replace arguments one by one if you don't want to try to debug your code.
(sorry for the "answer" it seems that i cannot add a remark)
I am assuming that you have all of your records in Insurances.txt on different lines as your data does have 13 distinct records there if one reads closely.
You should also follow what #jlordo is saying and change e.getMessage() to e.printStackTrace(). By doing that and running your code, I was getting
Having said that you should also trim all of your strings produced by your strLine.split(",") call. For example (without error checking) use this Integer.parseInt(array[0].trim()) instead of this Integer.parseInt(array[0]).
By doing the trim I was able to see the 'y' print 13 times.
You will never get 13 loops if your input file doesn't have 13 lines. Your program is expected to read them one line at a time.

Reading file data into LinkedList error

I am working on a code that reads data about customers from an input file and stores them into a linkedlist of objects of customer. the linked list implementation is not the JVM one. while reading the data using the readFile(), it's giving me a NumberFormatException: For input string: "Ben Affleck" error. here's the method. the basic idea of the logic is to read the first record initially and set it as the head of the linked list and then read the subsequent records. the error occurs during the if conditional when it checks for duplicate account id's. the way i coded it was if the id's match then skip those many number of lines to the next record. the Acd() method enters items in ascending order in the linkedlist. help would be greatly appreciated. kindly let me know if the question is unclear.
public static int readFile(String filename, LinkedList<Customer> review) throws IOException{
Scanner scan = new Scanner (new File (filename));
/*Reading the first record separatly*/
Customer head = new Customer();
Node<Customer> first = new Node<Customer>(head);
String[] a = scan.nextLine().split("=");
int accId = Integer.parseInt(a[1].trim());
a = scan.nextLine().split("=");
String name = a[1].toUpperCase().trim();
a = scan.nextLine().split("=");
String address =a[1].trim();
a = scan.nextLine().split("=");
String phone_number =(a[1].trim());
a = scan.nextLine().split("=");
String date_of_birth =(a[1].trim());
a = scan.nextLine().split("=");
double balance =(Double.parseDouble(a[1].trim()));
a= scan.nextLine().split("=");
String accType =(a[1].trim());
if (accType.equals("Saving")){
Customer temp = new Account1();
Node<Customer> firstItem = new Node<Customer>(temp);
first = firstItem;
}
else if(accType.equals("Checking")){
Customer temp = new Account2();
Node<Customer> firstItem = new Node<Customer>(temp);
first = firstItem;
}
else if(accType.equals("Fixed")){
Customer temp = new Account3();
Node<Customer> firstItem = new Node<Customer>(temp);
first = firstItem;
a = scan.nextLine().split("=");
((Account3)first.item).set_intRate(Double.parseDouble(a[1].trim()));
}
first.item.set_account_id(accId);
first.item.set_name(name);
first.item.set_address(address);
first.item.set_phone_number(phone_number);
first.item.set_date_of_birth(date_of_birth);
first.item.set_balance(balance);
review.head= first;
count = count+1;
scan.nextLine();// resets the buffer reader
while (scan.hasNext()&& count>0){
Customer item = new Customer();
Node<Customer> temp = new Node<Customer>(item);
String[] st = scan.nextLine().split("=");
Customer ctr = new Customer();
Node<Customer> counter = new Node<Customer>(ctr);
counter=review.head; // counter pointing to head
int i=0;
while(counter!=null){
if(Integer.parseInt(st[1].trim())== review.getItem(i).get_accountid()){ // checking for duplicate records
System.out.println("This account id is already in use so the record won't be read");
while(!scan.nextLine().equals(" "))
scan.nextLine();
scan.nextLine(); //to bring the reader back to the accoutnId
}
else
break;
int AccId = Integer.parseInt(st[1].trim());
st = scan.nextLine().split("=");
String AccName = st[1].toUpperCase().trim();
st = scan.nextLine().split("=");
String AccAdd =st[1].trim();
st = scan.nextLine().split("=");
String AccPhNum =(st[1].trim());
st = scan.nextLine().split("=");
String AccDob =(st[1].trim());
st = scan.nextLine().split("=");
double AccBal =(Double.parseDouble(st[1].trim()));
st= scan.nextLine().split("=");
String AccType =(st[1].trim());
if (AccType.equals("Saving")){
Customer a1 = new Account1();
Node<Customer>Item = new Node<Customer>(a1);
temp = Item;
} else if(AccType.equals("Checking")){
Customer a2 = new Account2();
Node<Customer>Item = new Node<Customer>(a2);
temp = Item;
} else if(AccType.equals("Fixed")){
Customer a3 = new Account3();
Node<Customer>Item = new Node<Customer>(a3);
temp = Item;
st = scan.nextLine().split("=");
((Account3)temp.item).set_intRate(Double.parseDouble(a[1].trim()));
}
temp.item.set_account_id(AccId);
temp.item.set_name(AccName);
temp.item.set_address(AccAdd);
temp.item.set_phone_number(AccPhNum);
temp.item.set_date_of_birth(AccDob);
temp.item.set_balance(AccBal);
if (scan.hasNextLine()){
scan.nextLine();
}
review.insertAcd(temp.item);
count= count+1;
counter=counter.next;
}
if (count>=30){
System.out.println("The number of records read has exceeded the limit and it will stop reading now");
break;
}
}
return count;
}
The input file is:
Account Id = 123
Name = Matt Damon
Address = 465 Ripley Boulevard, Oscar Mansion, Singapore 7666322
DOB = 10-10-1970
Phone Number = 790-3233
Account Balance = 405600.00
Account Type = Fixed
Fixed Daily Interest = 0.05
Account Id = 126
Name = Ben Affleck
Address = 200 Hunting Street, Singapore 784563
DOB = 25-10-1968
Phone Number = 432-4579
Account Balance = 530045.00
Account Type = Saving
Account Id = 65
Name = Salma Hayek
Address = 45 Mexican Boulevard, Hotel California, Singapore 467822
DOB = 06-04-73
Phone Number = 790-0000
Account Balance = 2345.00
Account Type = Checking
Account Id = 78
Name = Phua Chu Kang
Address = 50 PCK Avenue, Singapore 639798
DOB = 11-08-64
Phone Number = 345-6780
Account Balance = 0.00
Account Type = Checking
Account Id = 234
Name = Zoe Tay
Address = 100 Blue Eyed St, Singapore 456872
DOB = 15-02-68
Phone Number = 456-1234
Account Balance = 600.00
Account Type = Saving
Account Id = 2350
Name = Zoe Tay
Address = 100 Blue Eyed St, Singapore 456872
DOB = 15-02-68
Phone Number = 456-1234
Account Balance = 600.00
Account Type = Fixed
Fixed Daily Interest = 0.055
The first record has more lines (it has a "Fixed Daily Interest") than the second, so you may think you are reading in a String but it is actually a Double (or vice versa). So you will need to modify your code to either take into consideration this extra line or remove it from the first record as your code is expecting int, String, String, String, String, double, String whereas the first record is int, String, String, String, String, double, String, double.
This is not really the optimum solution to this problem, as you are repeating a chunk of code. It really could be in a single loop I think. It is definitely a type conversion problem like I initially said. You are attempting to get an integer out of a String that does not contain a number. Java is correctly telling you that there is no parsable Integer.
I will try and compile your code and see if I can pinpoint the exact error but what I have written above should give you enough of an idea to find out where the breakage is. Basically you think you are reading one line of your input file whereas you are actually on the line above or below.
Edit: Well I've hacked up your code and got it to compile. From an initial inspection it looks like that Matt Damon is OK but it is the second loop that is incorrect. You have an code that looks like this:
while (scan.hasNext()&& count>0){
Customer item = new Customer();
Node<Customer> temp = new Node<Customer>(item);
String[] st = scan.nextLine().split("=");
....
while(counter!=null){
if(Integer.parseInt(st[1].trim())== review.getItem(i).get_accountid()){
...
} else {
break;
}
}
}
The account number st[1].trim() (this is 126 from your input file by the way) does not match since Matt Damon is the only one so far, so the code breaks out of the inner while condition and then proceeds to read the next line - "Ben Affleck". Then it enters the inner while loop again and tried to do Integer.parseInt on "Ben Affleck" which as you see is a NumberFormatException.
Edit 2:
Having looked over your other questions it looks like you are getting the SO community to write a lot of the application for you! It is clear you are learning Java but this may not be the best way to learn Java in my opinion! Don't worry though, we've all been there :-)
Without stepping through your exact code I cannot really answer the question exactly. Note that it cannot be compiled standalone the form given above since it is missing dependent classes, a main() and import statements.
So my answer is going to be mostly pseudocode for your entire readFile function since I see no reason why the first record should be read in separately and I think the function is overly complex for what it needs to do.
Scanner scan = new Scanner (new File (filename));
// maintain collecction of Account Number <-> Account details
Map<Integer, Customer> accounts = new HashMap<Integer, Customer>();
String[] aLine = null;
while (scan.hasNext()) {
// read all of one account details
aLine= scan.nextLine().split("=");
int accId = Integer.parseInt(aLine[1].trim());
aLine= scan.nextLine().split("=");
String name = aLine[1].toUpperCase().trim();
etc...
String accType =(a[1].trim());
if (accType.equals("Saving")) {
...
} else {
...
}
// create Integer version of the accId to use as the key (the lookup)
// into the collection of details
Integer key = new Integer(accId);
if (accounts.containsKey(key)) {
// already added to the collection so
// no need to create a new Customer
} else {
// create new Customer
Customer c = new Customer();
c.set_account_id(accId);
etc...
// and add to the collection
c.put(key, c);
}
// skip over blank lines
while(!scan.nextLine().equals(" ")) {
scan.nextLine();
}
}
You may want to add some constraints to the while condition to limit the number of accounts added (as you have that in your existing code). For example:
while (scan.hasNext() && accounts.size() < 30) {
Hope this helps!

Categories