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)
Related
I am not experienced wit Arrays and I am getting this error in the debug console:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at com.company.SortTextFile.main(SortTextFile.java:28)
I've been looking in internet for how other people handle this included here in StackOverflow but I can't seem to understand why is it happening. I am trying to have this program get the input from a text file of multiple columns with 20 lines like this:
Eduardo 15 3.9 30000
And then using collection.sort to sort it using its id.
I am aware the arrays are 0-index however I don't know if I would need to specify the array size.
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.Double.*;
public class SortTextFile {
public static void main(String[] args) throws IOException {
// Creating BufferedReader object to read the input text file
BufferedReader reader = new BufferedReader(new FileReader(
"C:\\Users\\miche\\OneDrive\\Documentos\\University\\Algorithms\\Project\\StudentData.txt"));
// Creating ArrayList to hold Student objects
var studentRecords = new ArrayList<Student>();
// Reading Student records one by one
String currentLine = reader.readLine();
while (currentLine != null) {
String[] studentDetail = currentLine.split("\\s+");
String name = studentDetail[0];
int age = Integer.valueOf(studentDetail[1]);
double GPA = valueOf(studentDetail[2]);
int id = Integer.valueOf(studentDetail[3]);
// Creating Student object for every student record and adding it to
// ArrayList
studentRecords.add(new Student(name, age, GPA, id));
currentLine = reader.readLine();
}
// Sorting ArrayList studentRecords based on marks
Collections.sort(studentRecords, new idCompare());
// Creating BufferedWriter object to write into output text file
BufferedWriter writer = new BufferedWriter(new FileWriter(
"C:\\C:\\Users\\miche\\OneDrive\\Documentos\\University\\Algorithms\\Project\\output.txt"));
// Writing every studentRecords into output text file
for (Student student : studentRecords) {
writer.write(student.name);
writer.write(" " + student.age);
writer.write(" " + student.GPA);
writer.write(" " + student.id);
writer.newLine();
}
// Closing the resources
reader.close();
writer.close();
}
}
I made a Student class to compare the IDs.
public class Student extends SortTextFile {
String name;
int id;
int age;
double GPA;
public Student(String name, int id, double age, double GPA) {
this.name = name;
this.id = id;
this.age = (int) age;
this.GPA = GPA;
}
}
//idCompare Class to compare the marks
class idCompare implements Comparator<Student> {
#Override
public int compare(Student s1, Student s2) {
return s2.id - s1.id;}
}
Edit 1:
The text file just follows a format of Name/Age/GPA/ID:
Chipaldo 25 3.5 29000
Eduardo 15 3.9 30000
Ricardo 23 3.8 18000
Anthony 24 3.9 19000
Lombardo 29 2.0 22000
Romina 28 2.1 23000
Alex 25 3.1 13000
Sofia 21 2.2 24000
Vexler 24 2.2 25000
Albert 19 3.2 14000
John 24 3.0 15000
Melchor 14 2.9 16000
Bernardo 21 4.0 17000
Diego 19 2.1 26000
Miguelangel 25 2.0 27000
Edit 3: I managed to printout the Output in a new file. It sorted it based on age and not ID for some reason. Thank you for your help. I am going to try implement and Binary Insertion Sort to this program instead of doing Collection.sort Thanks.
If possible please be as detailed as possible with any suggestion. English is not my main language & I am slow at this. Thank you in advance
The message simply means that you have an array that only has 1 element in it and you are trying to access array element 2. This is one of those weird things in computer science (and Java as a language) because we start counting from zero rather than one, i.e. the first element in an array is indexed as studentDetail[0] and the second as studentDetail[1]. This is why you see the rather confusing "Index 1 out of bounds for length 1". The array being returned by currentLine.split(" ") only contains one string, not four, as you are expecting. You need to debug the code to find out why this is happening (from what you've provided this is not possible for someone else to answer).
your array seems to only have one entry. check if there is a problem with your string.split(" ")?
Use currentLine.split("\\s+"); This means that there may be one or more spaces or tabs or newlines between fields.
What you did will work correctly if and only if the fields are separated by one single space.
For debugging purpose print the length of the array using System.out.println(studentDetail.length);
Try This. Your code you did not closed writer thats why nothing is to in the output file.
public static void main(String[] args) throws IOException {
//Creating BufferedReader object to read the input text file
BufferedReader reader = new BufferedReader(new FileReader("E:\\Projects\\JavaBasics\\src\\data.txt"));
//Creating ArrayList to hold Student objects
var studentRecords = new ArrayList<Student>();
//Reading Student records one by one
String currentLine = null;
while ((currentLine = reader.readLine()) != null) {
if (!currentLine.isEmpty()) {
System.out.println(currentLine);
String[] studentDetail = currentLine.split(" ");
String name = studentDetail[0];
int age = Integer.valueOf(studentDetail[1]);
double GPA = Double.valueOf(studentDetail[2]);
int id = Integer.valueOf(studentDetail[3]);
studentRecords.add(new Student(name, age, GPA, id));
}
}
//Sorting ArrayList studentRecords based on marks
Collections.sort(studentRecords, new IdCompare());
//Creating BufferedWriter object to write into output text file
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(new File("E:\\Projects\\JavaBasics\\src\\dataout.txt")));
//Writing every studentRecords into output text file
for (Student student : studentRecords) {
System.out.println("Sorted :: " + student.name);
writer.write(student.name);
writer.write(" " + student.age);
writer.write(" " + student.GPA);
writer.write(" " + student.id);
writer.newLine();
}
} finally {
writer.close();
}
}
I tried to figure out the following problem for the last 20 hours, so I thought before I start thinking about jumping out of the window ;-), I better ask here for help:
I have a text file with following content:
ID
1
Title
Men and mice
Content
Lenny loves kittens
ID
2
Title
Here is now only the Title of a Book
ID
3
Content
Here is now only the Content of a Book
The problem as you can see is that there is either both title and content after id or only title after id.
I want to create text files which contain an ID value (for example 1) and the corresponding title value and/or content value.
The best I achieved was three lists. One with id values, one with title values and one with content values. But it is actually useless, because the information between id, content and title is lost.
I would really appreciate your held.
So you want to populate a collection of a class with three fields.
class Data {
int id;
String title;
String content;
// helper method to read a file and return a list.
public static List<Data> readAll(String filename) throws IOException {
// List we will return.
List<Data> ret = new ArrayList<Data>();
// last value we added.
Data last = null;
// Open a file as text so we can read the lines.
// us try-with-resource so the file is closed when we are done.
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
// declare a String and use it in a loop.
// read line and stop when we get a null
for (String line; (line = br.readLine()) != null; ) {
// look the heading.
switch (line) {
case "ID":
// assume ID is always first
ret.add(last = new Data());
// read the next line and parse it as an integer
last.id = Integer.parseInt(br.readLine());
break;
case "Title":
// read the next line and save it as a title
last.title = br.readLine();
break;
case "Content":
// read the next line and save it as a content
last.content = br.readLine();
break;
}
}
}
return ret;
}
}
Note: the only field which matters is ID. Content and Title are optional.
To get from 20 hours down to 5 minutes, you need to practice, a lot.
You can keep "the information between id, content and title" in your program if you create a Book class and then have a list of Book instances.
Book class:
public class Book {
private int id;
private String title;
private String content;
//...
//getters and setters
}
List of books:
private List<Book> books = new ArrayList<Book>();
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 );
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();
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!