asking about non-primitives arraylist - java

I have created ArrayList. How can i use this list to get method or attribute from the class. I tried but i could not reach any solution.
I tried to get into element in array list and get some attributes but i can't.
public static void printOptions() {
System.out.println("Welcome to our university!");
System.out.println("Operations:");
System.out.println("1- College");System.out.println("a) Number of Departments");System.out.println("b) Number of Courses");System.out.println("c) Number of Professors");System.out.println("d) Number of Students");System.out.println("e) Report");
System.out.println("2- Department");System.out.println("a) New");System.out.println("b) Number of Courses");System.out.println("c) Number of Students");System.out.println("d) Is Full");System.out.println("e) Enroll");System.out.println("f) Report");
System.out.println("3- Course");System.out.println("a) New");System.out.println("b) Number of Students");System.out.println("c) Assign");System.out.println("d) Is assigned");System.out.println("e) Professor Name");System.out.println("f) Is Full");System.out.println("g) Enroll");System.out.println("h) Report");
System.out.println("4- Professor");System.out.println("a) New");System.out.println("b) Display Salary");System.out.println("c) Get Raise");System.out.println("d) Report");
System.out.println("5- Student");System.out.println("a) New");System.out.println("b) Report");
System.out.println("6- Quit");
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
printOptions() ;
List<Department> departmentList;departmentList = new ArrayList<>();
List<Course> courseList ;courseList = new ArrayList<>();
List<Professor> proffList = new ArrayList<>() ;
List<Student> studentList;studentList = new ArrayList<>() ;
Scanner in = new Scanner(System.in) ;
int d = 0 , c = 0 , p = 0 , s=0 ;
College AinShams = new College() ;
while (true){
String option = in.nextLine() ;
if(!"6".equals(option)) {
if ("2a".equals(option)) { // Define new department
System.out.println("Department Name:");
String depName = in.nextLine() ;
System.out.println("Department Description:");
String depDescripe = in.nextLine() ;
System.out.println("Department Max Students:");
int max_num = in.nextInt() ;
in.nextLine() ;
Department Department_Name = new Department(depName, depDescripe, max_num);
// departmentList.add(Department_Name);
departmentList.add(d, Department_Name);
d++ ;
AinShams.setDepart(departmentList);
}
else if ("4a".equalsIgnoreCase(option)) {//new proff
System.out.println("Professor Firstname:");
String firstName = in.nextLine() ;
System.out.println("Professor Lastname:");
String lastName = in.nextLine();
System.out.println("Professor telephone:");
String telephone = in.nextLine();
System.out.println("Professor address:");
String address = in.nextLine();
System.out.println("Professor salary:");
double salary = in.nextDouble() ;
Professor proff = new Professor(firstName, lastName, telephone, address, salary);
proffList.add(p,proff) ;
p++ ;
AinShams.setProf(proffList);
}
else if ("2e".equalsIgnoreCase(option)) {//add student in department
System.out.println("Department:");
String dep= in.nextLine() ;
System.out.println("Student:");
String stu= in.nextLine();
// System.out.println(AinShams.getDepart());
AinShams.getDepart().
/*for (int i = 0; i < AinShams.getDepart().size(); i++) {
}*/
}
System.out.println("============");
System.out.println("Enter Operation");
System.out.println("============");
}else {break ;}
}
}
}
In condition (2e), I need to get methods and attributes in class which I assigned in array List

AinShams.getDepart() is referring to an object which you defined as data type College:
College AinShams = new College();
The rest of the College code is not in this fragment so I cannot tell whether the .getDepart() method exists. Either way, the College is not an ArrayList.
If you want to reach the methods and fields of objects inside an ArrayList something like the following would work. As an example I take the ArrayList called departmentlist, and use the get() method to return the 0th element from that list. Assuming the 0th element of that class is an object of type Department, the .name asks for the name field (again, assuming this name variable exists in the Department class). The .getName() would be a better way to get the name value but requires you coding this method in the Department class.
departmentlist.get(0).name
departmentlist.get(0).getName()
By the way, consider reducing some of the "System.out.println()" clutter in the top of your code by formatting your output with the "\n" new line key. Try these two examples using 1 system.out.println call to print two lines of text:
System.out.println("Welcome to our university!" + "\n" + "Operations:");
System.out.println("Welcome to our university! \nOperations:");

You want to add a new student to a department. Your College class has other attributes like list of departments, professors, etc.
Approach:
You can get the Department object from the array list, by the department name (property) passed by the user in case-2e. Then use that object to insert new student to its student's list.
Code:
Your code can be something like below (Pardon any compilation error as I haven't used any IDE. Follow the approach):
String dept = in.nextLine();
Department department = AinShams.getDepart().stream().filter(department -> department.getName().contentEquals(dept)).limit(1);
department.getStudentList().add(new Student());
Follow the link for non-stream version:
How to find an object in an ArrayList by property
OR Use the following method:
Department findDepartment(List<Department> deptList, String dept) {
for(Department department : deptList) {
if(department.getName().equals(dept)) {
return department;
}
}
return null;
}

Related

How can I create a loop to search through an object for the correct value in java?

I'm attempting to search through an object to see if a user's input matches what the program has stored, but I cannot figure out a way to make it work. I attempted to see if the value inputed by a user matched that of one in the userID spot for any of these Employee objects, but that didn't work. For example, here is the object:
Employee{userID='u1234567', userSalary=65000, userType=true}
Employee{userID='u1938562', userSalary=100000, userType=true}
Employee{userID='u1047218', userSalary=125000, userType=false}
Employee{userID='u1530078', userSalary=55000, userType=true}
Employee{userID='u1088621', userSalary=78400, userType=true}
Employee{userID='u2405234', userSalary=105000, userType=false}
Employee{userID='u1142592', userSalary=87500, userType=true}
Employee{userID='u1000092', userSalary=235000, userType=true}
Employee{userID='u1220433', userSalary=450000, userType=false}
Employee{userID='u1082304', userSalary=95000, userType=true}
My first function attempts to match the user's input with one of the userID's, but like I said it only works with the "u1234567"'s line. I have been attempting this for quite a while now, but I am relatively new to java and so I'm still learning. Below is my code, and where I commented out the "This is where I'm trying to loop through objects to look for a match" is where I would think to place this code, but I would greatly appreciate any feedback or better suggestions.
package homework4;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
public class main {
public static void main(String[] args) throws Exception {
// pass the path to the file as a parameter
Scanner file_in = new Scanner(new File("input.txt"));
Scanner in = new Scanner(System.in);
ArrayList<Employee> employees = new ArrayList<>();
// CREATE NEW ARRAY LIST FOR THE USERS
while (file_in.hasNextLine()) {
boolean isWorker = false;
String current_line = file_in.nextLine();
String[] line_split = current_line.split(",");
if (line_split[2].equals("1")) {
isWorker = true;
}
//Load the data To the List
employees.add(new Employee(line_split[0], Integer.parseInt(line_split[1]), isWorker));
}
ArrayList<Employee> copyEmployeesList1 = new ArrayList<>();
String userID = null;
//loop 4 times then create output.txt
for(int i = 0; i < 4; i++) {
// This is where I'm trying to loop through the object to look for a match
for(int b = 0; b < employees.size(); b++) {
employees.get(userID);
}
// User inputs userID and checks to see if theres a match
System.out.println("Enter employee ID of an employee?");
userID = in.nextLine();
for (Employee employee : employees){
if (employee.getUserID().equalsIgnoreCase(userID)) {
copyEmployeesList1.add(employee);
//System.out.println(employee);
break;
} else {
System.out.println("Incorrect value, please try again");
System.out.println("Enter employee ID of an employee?");
userID = in.nextLine();
break;
}
}
// User inputs user salary and checks if it matches the previous userID's lines salary.
System.out.println("Enter salary of the employee");
String userSalary = in.nextLine();
int userInput = Integer.parseInt(userSalary);
if(userInput == copyEmployeesList1.get(0).getUserSalary()) {
} else {
System.out.println("Incorrect value, please try again");
System.out.println("Enter salary of the employee");
}
// Redundant input my professor requires, but input a 1 or a 2
System.out.println("Is this in a manager or worker? (Enter 1 for worker 2 for manager)");
String userType = in.nextLine();
boolean choice;
choice = userType.equals("1");
employees.add(new Employee(userID, Integer.parseInt(userSalary), choice));
}
//compile salaries
for(Employee emp:employees) {
ManagerEmployee.calculate(emp);
WorkerEmployee.calculate(emp);
}
employees.forEach(System.out::println);
}
employees is an arraylist of Employee, you can only use .get to get by a specific index. You will need to use something like javas stream filter or a different method like in this tutorial.
ArrayList<Employee> employeesWithASpecificID = users.stream()
.filter(employee -> employee.getUserID() == userID)
.collect(Collectors.toList());

JAVA: using maps with the value as an array list of string

This code prompts the user asking their name and the school they attend. Storing both into a map. I then want to print out the school and the name of every person that attended that school in this format.
School : name, name , name. /new line
School : name, name , name etc.
.
.
.
However I keep getting null values for the name when trying to print
here is my code:
import java.util.*;
public class MapsAndArrayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String school;
String name;
//create the map with Arraylist as key value
Map<String, ArrayList<String>> sAtt = new HashMap<String, ArrayList<String>>();
do {
System.out.println("Enter your name: (type \"done\" when done)");
name = sc.nextLine().toUpperCase();
System.out.println("Enter the school you attend: ");
school = sc.nextLine().toUpperCase();
if (!sAtt.containsKey(school)) { // if school is not already in list, add it
ArrayList<String> names = new ArrayList<String>();
//add name to arraylist of names
names.add(name);
sAtt.put(school, names);
} else { // if school is in list just add name to list
ArrayList<String> names = sAtt.get(school);
names.add(name);
sAtt.replace(school, names);
}
} while (!(name.equals("DONE") || school.equals("DONE")));
// remove done from the list
sAtt.remove("DONE");
System.out.println("Here are the schools attended along with who goes there: ");
for (String s : sAtt.keySet()) {
System.out.println("\t" + s + ": " + sAtt.get(school));
}
}
}
The last for loop is using wrong key. Following would be right for loop:
for (String s : sAtt.keySet()) {
System.out.println("\t" + s + ": " + sAtt.get(s));
}
You are getting null because school variable has DONE as key which is removed in earlier statement.
Also, I would suggest using multi-map for this purpose.
https://google.github.io/guava/releases/21.0/api/docs/com/google/common/collect/Multimap.html

Reading a special txt file in java

What I want to do is read a text file that has humans and animals. It will compile but has an error when I try to run it. I think I need a for loop to read the stringtokenizer to decipher between the human and animal in the txt file so far this is my driver class.
txt file:
Morely,Robert,123 Anywhere Street,15396,4,234.56,2
Bubba,Bulldog,58,4-15-2010,6-14-2011
Lucy,Bulldog,49,4-15-2010,6-14-2011
Wilder,John,457 Somewhere Road,78214,3,124.53,1
Ralph,Cat,12,01-16-2011,04-21-2012
Miller,John,639 Green Glenn Drive,96258,5,0.00,3
Major,Lab,105,07-10-2012,06-13-2013
King,Collie,58,06-14-2012,10-05-2012
Pippy,cat,10,04-25-2015,04-25-2015
Jones,Sam,34 Franklin Apt B,47196,1,32.09,1
Gunther,Swiss Mountain Dog,125,10-10-2013,10-10-2013
Smith,Jack,935 Garrison Blvd,67125,4,364.00,4
Perry,Parrot,5,NA,3-13-2014
Jake,German Shepherd,86,11-14-2013,11-14-2013
Sweetie,tabby cat,15,12-15-2013,2-15-2015
Pete,boa,8,NA,3-15-2015
Source:
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.File;
import java.io.IOException;
/**
* This is my driver class that reads from a txt file to put into an array and uses the class refrences so it can use the menu and spit out
*
* #author ******
* #version 11/25/2015
*/
public class Driver
{
/**
* Constructor for objects of class Driver, what it does is read in the txt file gets the two class refrences and loops through to read through the whole file looking for string tokens to go to the next line
* and closes the file at the end also uses for loop to count number of string tokens to decipher between human and pets.
*/
public static void main(String[] args) throws IOException
{
Pet p;
Human h;
Scanner input;
char menu;
input = new Scanner(new File("clientdata.txt"));
int nBalance;
int id;
/**
* this while statement goes through each line looking for the string tokenizer ",". I want to count each "," to decipher between Human and Animal
*/
while(input.hasNext())
{
StringTokenizer st = new StringTokenizer(input.nextLine(), ",");
h = new Human();
h.setLastName(st.nextToken());
h.setFirstName(st.nextToken());
h.setAddress(st.nextToken());
h.setCiD(Integer.parseInt(st.nextToken()));
h.setVisits(Integer.parseInt(st.nextToken()));
h.setBalance(Double.parseDouble(st.nextToken()));
p = new Pet(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), st.nextToken(), st.nextToken());
}
/**
* this is my seond while statement that loops the case switch statements and asks the user for client ID
*/
menu = 'Y';
while(menu == 'y' || menu == 'Y') {
System.out.print("\nChose one:\n A- client names and outstanding balance \n B- client's pets, name, type and date of last visit\n C-change the client's outstanding balance: ");
menu = input.next().charAt(0);
System.out.print("Enter client ID: ");
id = input.nextInt();
h = new Human();
if(id == h.getCiD())//if the id entered up top is equal to one of the id's in the txt file then it continues to the menu
{
p = new Pet();
switch(menu)
{ case 'A':
System.out.println("client name: " + h.getFirstName() + "outstanding balance: " + h.getBalance());
break;
case 'B':
System.out.println("pet's name: " + p.getName() + "type of pet: " + p.getTanimal() + "date of last visit: " + p.getLastVisit());
break;
case 'C':
System.out.println("what do you want to change the clients balances to?");
input.close();
}
}
else// if not then it goes to this If statement saying that the Client does not exist
{
System.out.println("Client does not exist.");
}
}
}
}
You have a number of issues you need to overcome...
For each line, you need to determine the type of data the line represents
You need some way to keep track of the data you've loaded (of the clients and their pets)
You need some way to associate each pet with it's owner
The first could be done in a number of ways, assuming we can change the data. You could make the first token meaningful (human, pet); you could use JSON or XML instead. But lets assume for the moment, you can't change the format.
The key difference between the two types of data is the number of tokens they contain, 7 for people, 5 for pets.
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
// Parse owner
} else if (parts.length == 5) {
// Parse pet
} // else invalid data
For the second problem you could use arrays, but you would need to know in advance the number of elements you will need, the number of people and for each person, the number of pets
Oddly enough, I just noticed that the last element is an int and seems to represent the number of pets!!
Morely,Robert,123 Anywhere Street,15396,4,234.56,2
------------^
But that doesn't help us for the owners.
For the owners, you could use a List of some kind and when ever you create a new Human, you would simply add them to the List, for example...
List<Human> humans = new ArrayList<>(25);
//...
if (parts.length == 7) {
// Parse the properties
human = new Human(...);
humans.add(human);
} else if (parts.length == 5) {
Thirdly, for the pets, each Pet should associated directly with the owner, for example:
Human human = null;
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
//...
} else if (parts.length == 5) {
if (human != null) {
// Parse pet properties
Pet pet = new Pet(name, type, age, date1, date2);
human.add(pet);
} else {
throw new NullPointerException("Found pet without human");
}
}
Okay, so all this does, is each time we create a Human, we keep a reference to the "current" or "last" owner created. For each "pet" line we parse, we add it to the owner.
Now, the Human class could use either a array or List to manage the pets, either will work, as we know the expected number of pets. You would then provide getters in the Human class to get a reference to the pets.
Because out-of-context code can be hard to read, this is an example of what you might be able to do...
Scanner input = new Scanner(new File("data.txt"));
List<Human> humans = new ArrayList<>(25);
Human human = null;
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
String firstName = parts[0];
String lastName = parts[1];
String address = parts[2];
int cid = Integer.parseInt(parts[3]);
int vists = Integer.parseInt(parts[4]);
double balance = Double.parseDouble(parts[5]);
int other = Integer.parseInt(parts[6]);
human = new Human(firstName, lastName, address, cid, vists, balance, other);
humans.add(human);
} else if (parts.length == 5) {
if (human != null) {
String name = parts[0];
String type = parts[1];
int age = Integer.parseInt(parts[2]);
String date1 = parts[3];
String date2 = parts[4];
Pet pet = new Pet(name, type, age, date1, date2);
human.add(pet);
} else {
throw new NullPointerException("Found pet without human");
}
}
}
What about using split() function instead of using StringTokenizer?
Say, You can change your first while loop like below:
while (input.hasNext()) {
// StringTokenizer st = new StringTokenizer(input.nextLine(), ",");
String[] tokens = input.nextLine().split(",");
if (tokens.length == 7) {
h = new Human();
h.setLastName(tokens[0]);
h.setFirstName(tokens[1]);
h.setAddress(tokens[2]);
h.setCiD(Integer.parseInt(tokens[3]));
h.setVisits(Integer.parseInt(tokens[4]));
h.setBalance(Double.parseDouble(tokens[5]));
} else {
p = new Pet(tokens[0], tokens[1], Integer.parseInt(tokens[2]), tokens[3], tokens[4]);
}
}
And for keeping track of which pet belongs to which human, you can append an arrayList of type Pet in Human class like below:
ArrayList<Pet> pets = new ArrayList<>();
And say you have another ArrayList of type Human named humans in the main function. So, you could append in if block like:
humans.add(h);
and in the else section, you could append in else block:
humans.get(humans.size()-1).pets.add(p);
You can try something like this -
Populate a map and then using that you can assign values according to your requirement.
public void differentiate(){
try {
Scanner scan=new Scanner(new BufferedReader(new FileReader("//your filepath")));
Map<String,List<String>> map=new HashMap<String, List<String>>();
while(scan.hasNextLine()){
List<String> petList=new ArrayList<String>();
String s=scan.nextLine();
String str[]=s.split(",");
String name=str[1]+" "+str[0];
int petCount=Integer.parseInt(str[str.length-1]);
for(int i=1;i<=petCount;i++){
String petString=scan.nextLine();
petList.add(petString);
}
map.put(name, petList);
}
Set<String> set=map.keySet();
for(String str:set){
System.out.println(str+" has "+map.get(str)+" pets");
}
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}

JAVA, Read from a text file, print out info from the array

very new to Java and I have a question
I was given an text file, and asked to find the employee who earn the most, and print out their info (fName, Lname, ID)
the text file was like so:
Date of birth fName lName wage hr work emp ID
12/03/1929 Detzk Fyshe 37 49 07036310484
04/17/1930 Cauus Walden 38 52 63612537553
07/12/1930 Barth Harling 43 72 42101524036
07/16/1930 Bartl Barnhill 43 62 48621748867
I manage to find the max wage. But have no idea how to print out the info
Here my code so far:
public static void main(String[] args) {
File inFile = new File ("dataSet.txt");
ArrayList <String> inData = new ArrayList <String>();
String strline;
try
{
FileInputStream fstream = new FileInputStream(inFile);
BufferedReader br = new BufferedReader (new InputStreamReader (fstream));
while ((strline = br.readLine()) != null)
{
strline = strline.trim();
if ((strline.length()!=0)) inData.add(strline);
}
} catch (Exception e) {
System.err.println("Error CANNOT FIND FILE!");
}
// Max wage finder *start*
int maxWage=0;
for (int i=0; i<inData.size(); i++){
String [] word = inData.get(i).split(" ");
int wage=Integer.parseInt (word[3]);
int hrWork=Integer.parseInt (word[4]);
int earn = wage*hrWork;
if (earn>maxWage){
maxWage=earn;
}
}
System.out.println("Max Wage in $:"+maxWage);
//max wage finder *end*
If you're reading in employee data, then an object-oriented solution to the problem is to create an Employee class with strongly typed (dates as Dates, and integers as ints) attributes that model the contents of the file.
In addition to the instance variables that would store the actual data of each Employee, you might want to override the toString() method in the class so that the employee information can be easily output, for example to System.out. Also, you would need a getter for the "total salary" of an employee (which you calculate with wage * hrWork) so that the salaries of two employees can be compared externally, e.g. by a Comparator.
All in all, the code could look like this for the relevant parts:
private static final DateFormat FORMATTER = new SimpleDateFormat("MM/dd/yyyy");
...
List<Employee> employees = new ArrayList<Employee>();
...
// within the loop that reads the file:
String[] columns = strline.split(" ");
employees.add(new Employee(
FORMATTER.parse(columns[0]), // DOB,
columns[1], // first name
columns[2], // last name
Integer.parseInt(columns[3]), // wage
Integer.parseInt(columns[4]), // hr
columns[5]) // employee id
);
...
// after all lines have been read, output the employee with largest wage
Employee earnsMost = Collections.max(employees, new Comparator<Employee>() {
#Override
public int compare(Employee e1, Employee e2) {
return e1.getTotalSalary() - e2.getTotalSalary();
}
});
System.out.println(earnsMost + " earns most.");

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