Element update for Java Util List [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have an ArrayList for Patients in little hospital system and need to write a method to update the patient information. This method should take an integer called "id", match this id with all id's in Patient ArrayList and change some information in that object. How can I iterate this list? Thanks.
This is my Patient Class
import java.util.ArrayList;
import java.util.List;
public class Patient {
String strName,strSurname,strAddress,strDepartment,strGender;
int iId,iClass,iDob;
List<Entry> entries = new ArrayList<Entry>();
long longTel;
boolean boolAllergy,boolChronicDisease,boolRegularMedicine;
public boolean isBoolAllergy() {
return boolAllergy;
}
public void setBoolAllergy(boolean boolAllergy) {
this.boolAllergy = boolAllergy;
}
public boolean isBoolChronicDisease() {
return boolChronicDisease;
}
public void setBoolChronicDisease(boolean boolChronicDisease) {
this.boolChronicDisease = boolChronicDisease;
}
public boolean isBoolRegularMedicine() {
return boolRegularMedicine;
}
public void setBoolRegularMedicine(boolean boolRegularMedicine) {
this.boolRegularMedicine = boolRegularMedicine;
}
public String getStrName() {
return strName;
}
public void setStrName(String strName) {
this.strName = strName;
}
public String getStrSurname() {
return strSurname;
}
public void setStrSurname(String strSurname) {
this.strSurname = strSurname;
}
public String getStrAddress() {
return strAddress;
}
public void setStrAddress(String strAddress) {
this.strAddress = strAddress;
}
public String getStrDepartment() {
return strDepartment;
}
public void setStrDepartment(String strDepartment) {
this.strDepartment = strDepartment;
}
public int getiId() {
return iId;
}
public void setiId(int iId) {
this.iId = iId;
}
public long getlongTel() {
return longTel;
}
public void setiTel(long iTel) {
this.longTel = iTel;
}
public int getiClass() {
return iClass;
}
public void setiClass(int iClass) {
this.iClass = iClass;
}
public int getiDob() {
return iDob;
}
public void setiDob(int iDob) {
this.iDob = iDob;
}
public String getStrGender() {
return strGender;
}
public void setStrGender(String strGender) {
this.strGender = strGender;
}
public void Details() {
System.out.println("*********************************");
System.out.println("Patient Id: " + getiId());
System.out.println("Name: " + getStrName() + " Surname: " + getStrSurname());
System.out.println("Address: " + getStrAddress() + " Department: " + getStrDepartment() + " Gender: " + getStrGender());
System.out.println("Class: " + getiClass() + " Date of birth: " + getiDob() + " Tel: " + getlongTel());
System.out.println("Chronical Disease? " + isBoolChronicDisease());
System.out.println("Any Allergy? " + isBoolAllergy());
System.out.println("Using regular drugs?" + isBoolRegularMedicine());
System.out.println("*********************************");
}
}
And this is the main class that uses Patient class
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class Main {
static List<Doctor> listDoctors = new ArrayList<Doctor>();
static List<Nurse> listNurses = new ArrayList<Nurse>();
static List<Patient> listPatients = new ArrayList<Patient>();
static String strUserName = "admin";
static String strPass = "password";
public static void main(String[] args) {
#SuppressWarnings("unused")
int iChoice;
boolean exit = false;
boolean boolAccess = Login();
if (boolAccess) {
while(!exit) {
iChoice = Menu();
switch(iChoice) {
case 1:
AddDoctor();
break;
case 2:
AddNurse();
break;
case 3:
AddPatient();
break;
case 4:
ListDoctors();
break;
case 5:
ListNurses();
break;
case 6:
ListPatients();
break;
case 8:
ChangeUserName();
break;
case 9:
ChangePass();
break;
//Hastalığa göre hastalar listelenecek
//Kronik hastlalıkları olan hastalar listelenecek
//Sigortasını yatırmayan hastalar listelenecek
//delete ve update olayları
//Hastaneye sevkedilen hastalar listelenecek
//Yatılı kalan hastalar listelensin
//Raporlu olan entryler listelenecek
//Kayıt girilirken eğer hasta ismi ilk defa giriliyorsa önce hasta kaydı yapın diye uyarı cıkacak
case 15:
exit = true;
break;
}
}
}
}
private static void ChangeUserName() {
Scanner scan = new Scanner(System.in);
if(Login()) {
System.out.println("Enter new User Name:");
strUserName = scan.next();
System.out.println("Saved..");
}
}
private static void ChangePass() {
Scanner scan = new Scanner(System.in);
if(Login()) {
System.out.println("Enter new Password:");
strPass = scan.next();
System.out.println("Saved..");
}
}
private static void ListNurses() {
Iterator<Nurse> it = listNurses.iterator();
while(it.hasNext()) {
Nurse nur = (Nurse) it.next();
nur.Details();
}
}
private static void ListPatients() {
Iterator<Patient> it = listPatients.iterator();
while(it.hasNext()) {
Patient patient = (Patient) it.next();
patient.Details();
}
}
public static boolean Login() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Username: ");
if(strUserName.contentEquals(scan.next())) {
System.out.println("Enter Password:");
if(strPass.contentEquals(scan.next())) {
return true;
}
else
System.out.println("Wrong password");
return Login();
}
System.out.println("Wrong user name");
return Login();
}
public static int Menu() {
Scanner scan = new Scanner(System.in);
System.out.println("Choose one of the following order:");
System.out.println("1.Enter new Doctor");
System.out.println("2.Enter new Nurse");
System.out.println("3.Enter new Patient");
System.out.println("4.List all doctors");
System.out.println("5.List all nurses");
System.out.println("6.List all patients");
System.out.println("8.Change user name");
System.out.println("9.Change password");
System.out.println("15.Exit");
return scan.nextInt();
}
private static void ListDoctors() {
Iterator<Doctor> it = listDoctors.iterator();
while(it.hasNext()) {
Doctor doc = (Doctor) it.next();
doc.Details();
}
}
private static void AddDoctor() {
Doctor doctor;
String strName,strSurname,strSpeciality;
int iSSN;
Scanner scan = new Scanner(System.in);
System.out.println("Enter name:");
strName=scan.next();
System.out.println("Enter surname:");
strSurname = scan.next();
System.out.println("Enter speciality");
strSpeciality = scan.next();
System.out.println("Enter SSN");
iSSN = scan.nextInt();
doctor = new Doctor(strName,strSurname,strSpeciality,iSSN);
listDoctors.add(doctor);
System.out.println("Saved..");
}
private static void AddNurse() {
Nurse nurse;
String strName,strSurname;
int iSSN;
Scanner scan = new Scanner(System.in);
System.out.println("Enter name:");
strName=scan.next();
System.out.println("Enter surname:");
strSurname = scan.next();
System.out.println("Enter SSN");
iSSN = scan.nextInt();
nurse = new Nurse(strName,strSurname,iSSN);
listNurses.add(nurse);
System.out.println("Saved..");
}
private static void AddPatient() {
Patient patient = new Patient();
Scanner scan = new Scanner(System.in);
System.out.println("Enter name:");
patient.setStrName(scan.next());
System.out.println("Enter surname:");
patient.setStrSurname(scan.next());
System.out.println("Enter date of birth(DDMMYYYY)");
patient.setiDob(scan.nextInt());
System.out.println("Enter address:");
patient.setStrAddress(scan.next());
System.out.println("Enter department:");
patient.setStrDepartment(scan.next());
System.out.println("Enter gender:");
patient.setStrGender(scan.next());
System.out.println("Enter Telephone number:");
patient.setiTel(scan.nextLong());
System.out.println("Enter id:");
patient.setiId(scan.nextInt());
System.out.println("Enter class:");
patient.setiClass(scan.nextInt());
System.out.println("Does patient have any chronical disease? (Y/N)");
if(scan.next().contentEquals("Y"))
patient.setBoolChronicDisease(true);
else
patient.setBoolChronicDisease(false);
System.out.println("Does patient use any regular drugs? (Y/N)");
if(scan.next().contentEquals("Y"))
patient.setBoolRegularMedicine(true);
else
patient.setBoolRegularMedicine(false);
System.out.println("Does patient have any allergies?");
if(scan.next().contentEquals("Y"))
patient.setBoolAllergy(true);
else
patient.setBoolAllergy(false);
listPatients.add(patient);
}
private static void SearchPatientById(int id) {
Iterator<Patient> it = listPatients.iterator();
while(it.hasNext()) {
Patient patient = (Patient) it.next();
if(it.next().getiId() == id)
patient.Details();
}
}
}

With a slight modification your searchPatientById can return the found patient object:
private static Patient searchPatientById(int id) {
Iterator<Patient> it = listPatients.iterator();
while(it.hasNext()) {
Patient patient = (Patient) it.next();
if(patient.getiId() == id)
return patient;
}
// if not found return null
return null;
}
Note that I remove your double call to next()
That way, you can do something like
Patient foundPatient = searchPatientById(idToFind);
if (foundPatient != null) {
foundPatient.setBoolAllergy(patientsAllergyState);
} else {
// whatever you need to do if the patient cannot be found
}
Also note that in Java it's not common to encode the variable type into the variable names, but there's a universally followed naming convention

Related

Expression expected in switch case method call

My Java code is a simple CRM using user input to detail a lead's information. But that's not important. My trouble here is I'm trying to write the objects in my ArrayList<> into a .txt file.
I have the method to write the objects done but this line of code:
case "20" : {
saveCustomerToFile(leadfilepath,);
break;
}
The error says expression is expected but I don't exactly know what to put there.
Here's my code:
Main Class:
public class Main {
private static int leadsId = 0;
private static int interactionId = 0;
private static LeadsManager leadsManager = new LeadsManager();
private static InteractionsManager interactionsManager = new InteractionsManager();
public static void main(String[] args) {
String leadfilepath = "leads.txt";
//Declare Scanner
Scanner input = new Scanner(System.in);
System.out.print("[MENU] \n"
+ "===[MANAGING LEADS]=== \n"
+ "1) View all Leads \n"
+ "2) Create new Leads \n"
+ "3) Update a lead \n"
+ "4) Delete a lead \n"
+ "===[MANAGING INTERACTIONS]=== \n"
+ "5) View all Interactions \n"
+ "6) Create new Interactions \n"
+ "7) Update an Interaction \n"
+ "8) Delete an Interaction \n"
+ "===[Reporting and Statistics]===\n"
+ "10) N/A\n"
+ "11) N/A\n"
+ "12) N/A\n"
+ "===[Save Progress]===\n"
+ "20) Save leads arrays data into file.\n"
+ "Please input the desired function:");
while(true){
String answer = input.nextLine();
switch (answer){
case "1" : {
printLeads();
break;
}
case "2" : {
LeadMethod();
break;
}
case "3": {
String leadId = enterLeadIdPrompt();
updateLeads(leadId);
break;
}
case "4" : {
String leadId = enterLeadIdPrompt();
deleteLeads(leadId);
break;
}
case "5" : {
System.out.println("Printing all the sales people in the list ...");
System.out.println(" ");
printAllInteractions();
break;
}
case "6" : {
addInteractionInfo();
break;
}
case "7" : {
String interactionId = enterInteractionIdPrompt();
updateInteractionInfo(interactionId);
break;
}
case "8" : {
String interactionId = enterInteractionIdPrompt();
deleteInteractionInfo(interactionId);
break;
}
case "20" : {
saveCustomerToFile(leadfilepath,);
break;
}
}
}
}
///////////////////////Methods for Lead///////////////////////////////////
////Main method for creating leads/////
public static void LeadMethod(){
Leads leads = createLeadsObject();
if(leadsManager.addLeads(leads)){
System.out.println("Added Lead Successfully! \n" + leads);
}
else{
System.out.println("Adding Lead failed!");
}
}
public static void saveCustomerToFile(Leads lead, String leadfilepath){
try{
FileWriter leadfw = new FileWriter(leadfilepath, true);
BufferedWriter leadbw = new BufferedWriter(leadfw);
PrintWriter leadpw = new PrintWriter(leadbw);
leadpw.println(lead.toString());
leadpw.flush();
leadpw.close();
JOptionPane.showMessageDialog(null, "Leads saved!");
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Leads not saved!");
}
}
/////Creating the Lead Object from the Class and User input////////
private static Leads createLeadsObject(){
Scanner leadsInfoInput = new Scanner(System.in);
Leads leads = new Leads();
System.out.println("Enter Leads Data:");
leads.setLead_id(String.format("lead_%03d", leadsId++));
System.out.print("Name: ");
String Name = leadsInfoInput.nextLine();
leads.setName(Name);
System.out.print("Date of Birth (MM/DD/YYYY) : ");
String DateOfBirth = leadsInfoInput.nextLine();
leads.setDoB(DateOfBirth);
System.out.print("Gender (Male - 0, Female - 1) : ");
String Gender = leadsInfoInput.nextLine();
leads.setGender(Gender);
System.out.print("Phone Number : ");
String PhoneNumber = leadsInfoInput.nextLine();
leads.setPhone(PhoneNumber);
System.out.print("Email : ");
String Email = leadsInfoInput.nextLine();
leads.setEmail(Email);
System.out.print("Address : ");
String Address = leadsInfoInput.nextLine();
leads.setAddress(Address);
return leads;
}
////Printing out the leads on the console/////
private static void printLeads() { leadsManager.printAllLeads(); }
////Deleting a lead by ID////
private static void deleteLeads(String lead_id){
boolean isDeleted = leadsManager.deleteLeads(lead_id);
if(isDeleted){System.out.println("Deleting lead from the list...");
System.out.println("Deleted " + lead_id + " successfully!");
}else{
System.out.println("Delete lead failed!");
}
}
////Method to enter desired Lead ID////
private static String enterLeadIdPrompt(){
System.out.print("Enter customer id : ");
Scanner del = new Scanner(System.in);
return del.nextLine();
}
/////Method for updating a lead's data///////
private static void updateLeads(String lead_id) {
boolean isUpdated = leadsManager.updateLeads(lead_id);
if(isUpdated){
System.out.println("Update customer successful!");
}else{
System.out.println("Update customer failed.");
}
}
/////////////////////////////////////////////////////////////////
//////////////////////Interactions Section///////////////////////
///Method to call for adding Interaction
private static void addInteractionInfo() {
Interactions interaction = createInteractionObject();
boolean isAdded = interactionsManager.addInteraction(interaction);
if(isAdded){
System.out.println("Interaction added successfully!\n" + interaction);
}else{
System.out.println("Interaction add failed !");
}
}
////Method for Asking the Interaction's ID////
private static String enterInteractionIdPrompt(){
System.out.print("Enter model.Interaction Id : ");
Scanner interactionIdInput = new Scanner(System.in);
return interactionIdInput.nextLine();
}
//////Method to call for deleting an Interaction
private static void deleteInteractionInfo(String interactionId) {
boolean isDeleted = interactionsManager.deleteInteraction(interactionId);
if(isDeleted){
System.out.println("Delete interaction information successful!");
}else{
System.out.println("Delete interaction information failed.");
}
}
////Method to call for Updating Interaction's data
private static void updateInteractionInfo(String interactionId) {
boolean isUpdated = interactionsManager.updateInteraction(interactionId);
if(isUpdated){
System.out.println("Update interaction information successful!");
}else{
System.out.println("Update interaction information failed.");
}
}
///Method to call for printing interactions///
private static void printAllInteractions() {
interactionsManager.printAllInteractions();
}
/////User Input to create data for the Interaction object
private static Interactions createInteractionObject(){
Scanner interactionInfoInput = new Scanner(System.in);
Interactions interaction = new Interactions();
interaction.setInter_id(String.format("inter_%03d", interactionId++));
System.out.print("Date of interaction (MM/DD//YYYY) : ");
String dateOfInteraction = interactionInfoInput.nextLine();
interaction.setDoI(dateOfInteraction);
System.out.print("Lead ID : ");
String leadId = interactionInfoInput.nextLine();
Leads lead = leadsManager.getLeadsById(leadId);
if(lead == null){
while(lead == null){
System.out.println("Wrong customer id, please try again!");
leadId = interactionInfoInput.nextLine();
lead = leadsManager.getLeadsById(leadId);
}
}
interaction.setLead_id(lead);
System.out.print("Interaction Method (SNS / email / telephone / face to face) : ");
String method = interactionInfoInput.nextLine();
interaction.setMeans(method);
System.out.print("Potential (P - positive, NEG - negative, NEU - neutral) : ");
String potential = interactionInfoInput.nextLine();
interaction.setPotential(potential);
return interaction;
}
}
My Leads class:
public class Leads {
private String lead_id;
private String Name;
private String DoB;
private String Gender;
private String Phone;
private String Email;
private String Address;
//The Lead constructor
public Leads(String lead_id, String Name, String DoB, String Gender, String Phone, String Email, String Address){
this.lead_id = lead_id;
this.Name = Name;
this.DoB = DoB;
this.Gender = Gender;
this.Phone = Phone;
this.Email = Email;
this.Address = Address;
}
public Leads() {
}
///Mutators and Accessors////
public String getLead_id() {
return lead_id;
}
public void setLead_id(String lead_id) {
this.lead_id = lead_id;
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public String getDoB(){
return DoB;
}
public void setDoB(String DoB){
this.DoB = DoB;
}
public String getGender(){
return Gender;
}
public void setGender(String Gender){
this.Gender = Gender;
}
public String getPhone(){
return Phone;
}
public void setPhone(String Phone){
this.Phone = Phone;
}
public String getEmail(){
return Email;
}
public void setEmail(String Email){
this.Email = Email;
}
public String getAddress(){
return Address;
}
public void setAddress (String Address){
this.Address = Address;
}
#Override
public String toString() {
return "ID: "+lead_id + ", Name: " + Name +", DOB: " + DoB + ", Gender: " + Gender + ", Phone
Number: " + Phone + ", Email: " + Email + ", Address: " + Address;
}
}
And my LeadsManager class:
private ArrayList<Leads> leads = new ArrayList<>();
public ArrayList<Leads> getLeads(){
return leads;
}
///Actual method to call a Lead from its ID/////
public Leads getLeadsById(String lead_id){
for (int i = 0; i < leads.size(); i++){
if(lead_id.equals(leads.get(i).getLead_id())){
return leads.get(i);
}
}
return null;
}
///Adding a lead////
public boolean addLeads(Leads lead){
return leads.add(lead);
}
////Actual printing////
public void printAllLeads(){
for (int i = 0; i < leads.size(); i++) {
System.out.println(leads.get(i));
}
if(leads.size()==0){
System.out.println("The list is empty.");
}
}
///Actual deleting////
public boolean deleteLeads(String lead_id){
Leads lead = getLeadsById(lead_id);
if(lead == null){
return false;
}else{
return leads.remove(lead);
}
}
////////Updating Data//////
/////Might not work!!! Duan check xem co dung dc khong. Xong thi xoa line note nay/////
public boolean updateLeads(String lead_Id){
Leads leads = getLeadsById(lead_Id);
if(leads == null){
return false;
}
printLeadUpdateManual();
Scanner s = new Scanner(System.in);
boolean isDone = false;
String newInfo = "";
Interactions inter = null;
while(!isDone){
String target = s.nextLine();
switch (target){
case "name" : {
newInfo = updateInfoPrompt(target);
// leads.setName(newInfo);
boolean isValid = InputValidator.getInstance().validateName(newInfo);
if(isValid){
JOptionPane.showMessageDialog(null,"valid form!");
leads.setName(newInfo);
}else{
JOptionPane.showMessageDialog(null,"Invalid");
}
break;
}
case "dob" : {
System.out.print("enter new date of birth(MM/DD/YYYY) : ");
String newDate = new Scanner(System.in).nextLine();
boolean isValid = InputValidator.getInstance().validateBirthDay(newDate);
if(isValid){
leads.setDoB(newDate);
}else{
System.out.println("Invalid birthday form!");
}
break;
}
case "gender" : {
newInfo = updateInfoPrompt(target);
// leads.setGender(newInfo);
boolean isValid = InputValidator.getInstance().validateGender(newInfo);
if(isValid){
JOptionPane.showMessageDialog(null,"valid form!");
leads.setGender(newInfo);
}else{
JOptionPane.showMessageDialog(null,"Invalid");
}
break;
}
case "phone" : {
newInfo = updateInfoPrompt(target);
// leads.setName(newInfo);
boolean isValid = InputValidator.getInstance().validatePhoneNumber(newInfo);
if(isValid){
JOptionPane.showMessageDialog(null,"valid form!");
leads.setPhone(newInfo);
}else{
JOptionPane.showMessageDialog(null,"Invalid");
}
break;
}
case "email" : {
newInfo = updateInfoPrompt(target);
// leads.setName(newInfo);
boolean isValid = InputValidator.getInstance().validateEmail(newInfo);
if(isValid){
JOptionPane.showMessageDialog(null,"valid form!");
leads.setEmail(newInfo);
}else{
JOptionPane.showMessageDialog(null,"Invalid");
}
break;
}
case "address" : {
newInfo = updateInfoPrompt(target);
// leads.setName(newInfo);
boolean isValid = InputValidator.getInstance().validateAddress(newInfo);
if(isValid){
JOptionPane.showMessageDialog(null,"valid form!");
leads.setAddress(newInfo);
}else{
JOptionPane.showMessageDialog(null,"Invalid");
}
break;
}
case "0" : {
isDone = true;
break;
}
default : {
System.out.println("Wrong Input !");
printLeadUpdateManual();
break;
}
}
}
return true;
}
private void printLeadUpdateManual(){
System.out.println("Which information would you like to update?");
System.out.println("OPTIONS : [name, dob (MM/DD/YYYY), gender, phone, email, address]");
System.out.println("Enter '0' when update is complete.");
}
private String updateInfoPrompt(String updateTarget){
System.out.println("Type new "+ updateTarget+" to update: ");
return new Scanner(System.in).nextLine();
}
in the beginning of your 'saveCustomerToFile' function we can see it is expecting two objects: a 'Leads' object and a 'String' object:
public static void saveCustomerToFile(Leads lead, String leadfilepath){
yet in your switch function you only send it one, in the 'Leads' object place and a comma:
case "20" : {
saveCustomerToFile(leadfilepath,);
you need to specify add a lead object and place the objects in the correct order the function expects for the program to work properly.
something like this:
case "20" : {
saveCustomerToFile(lead_object, leadfilepath);
break;
}

ArrayList gets overwritten everytime a new instance is created

I'm a new programmer,
I'm terribly sorry for the walls of code, but I simply can't find the error.
I am tring to create an arrayList that stores input values, but everytime I create the 2nd instance, the first instance gets overwritten. It does print two instances, but both instances have the same value.
Main block:
The problem area is at the bottom of this code, "switch sc1" and "switch s2, case 2"
package com.company;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
User user = new User(null, null, null, null, null);
Login login = new Login(null, null, null, null, null);
Stream stream = new Stream(null, null, null, null, 0, null, null);
List list = new List(null, null, null, null, 0, null, null);
ArrayList<Stream> joinableList = new ArrayList<Stream>();
ArrayList<Stream> completedList = new ArrayList<Stream>();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM-yyyy HH:mm");
boolean showRoom = false;
while (showRoom == false) {
System.out.println("\nWelcome to ShowRoom\n\nPress 1 to login\nPress 2 to create a user\n");
Scanner choice1 = new Scanner(System.in);
System.out.print("Input: ");
int s1 = choice1.nextInt();
switch (s1) {
case 1:
System.out.print("\nEnter Username: ");
Scanner scanUsername = new Scanner(System.in);
String username = scanUsername.nextLine();
user.setUsername(username);
System.out.print("\nEnter Password: ");
Scanner scanPassword = new Scanner(System.in);
String password = scanPassword.nextLine();
user.setPassword(password);
login.verifyLogin(username, password);
break;
case 2:
System.out.print("\nChoose Username: ");
Scanner scanChooseUsername = new Scanner(System.in);
username = scanChooseUsername.nextLine();
user.setUsername(username);
user.saveUsername();
System.out.print("\nChoose Password: ");
Scanner scanChoosePassword = new Scanner(System.in);
password = scanChoosePassword.nextLine();
user.setPassword(password);
user.savePassword();
break;
}
boolean loggedIn = false;
while (loggedIn == false) {
System.out.println("\nWelcome to your dashboard " + user.username + "\n\nPress 1 to create a stream\nPress 2 to view joinable streams\nPress 3 to view completed streams");
Scanner choice2 = new Scanner(System.in);
System.out.print("\nInput: ");
int s2 = choice2.nextInt();
switch (s2) {
case 1:
String listUsername = user.username;
stream.setListUsername(user.username);
Scanner chooseTitle = new Scanner(System.in);
System.out.print("\nChoose title: ");
String title = chooseTitle.nextLine();
stream.setTitle(title);
System.out.println("\nYou have chosen: " + stream.title);
Scanner chooseGenre = new Scanner(System.in);
System.out.print("\nChoose genre:\n\nPress 0 for " + stream.genreArray[0] + "\nPress 1 for " + stream.genreArray[1] + "\nPress 2 for " + stream.genreArray[2] + "\n\nInput: ");
int chosenGenre = chooseGenre.nextInt();
String genre = stream.genreArray[chosenGenre];
stream.setGenre(genre);
System.out.println("\nYou have chosen: " + stream.genre);
Scanner chooseType = new Scanner(System.in);
System.out.print("\nChoose type:\n\nPress 0 for " + stream.typeArray[0] + "\nPress 1 for " + stream.typeArray[1] + "\nPress 2 for " + stream.typeArray[2] + "\n\nInput: ");
int chosenType = chooseType.nextInt();
String type = stream.typeArray[chosenType];
stream.setType(type);
System.out.println("\nYou have chosen: " + stream.type);
Scanner choosePrice = new Scanner(System.in);
System.out.print("\nChoose price: ");
double price = choosePrice.nextDouble();
stream.setPrice(price);
System.out.println("\nYou have chosen: " + stream.price);
Scanner chooseStartTimeDate = new Scanner(System.in);
System.out.print("\nChoose start time and date: \n\nInsert time and date in this format: dd/mm-yyyy hh:mm\n\nInput: ");
String startTimeDate = chooseStartTimeDate.nextLine();
stream.setStartTimeDate(startTimeDate);
System.out.println("\nYou have chosen " + stream.startTimeDate);
Scanner chooseEndTimeDate = new Scanner(System.in);
System.out.print("\nChoose end time and date: \n\nInsert time and date in this format: dd/mm-yyyy hh:mm\n\nInput: ");
String endTimeDate = chooseEndTimeDate.nextLine();
stream.setEndTimeDate(endTimeDate);
System.out.println("\nYou have chosen " + stream.endTimeDate);
Scanner confirmStream = new Scanner(System.in);
System.out.print("\nDo you want to create a stream, with the following details?\n\nTitle: " + title + "\nGenre: " + genre + "\nType: " + type + "\nPrice: " + price + "\nStart date and time: " + startTimeDate + "\nEnd date and time: " + endTimeDate + "\n\nPress 1 to confirm\nPress 2 to go back\n\nInput: ");
int sc1 = confirmStream.nextInt();
switch (sc1) {
case 1:
list.addJoinableList(stream);
System.out.println("\nStream has been created and added to list");
loggedIn = false;
break;
case 2:
loggedIn = false;
break;
}
case 2:
list.printJoinableList();
break;
case 3:
System.out.println("\nCompleted stream list");
break;
}
}
}
}
}
Stream block:
This block is used to inherit the properties for use in the class "List"
package com.company;
import java.time.LocalDateTime;
public class Stream {
protected String listUsername;
protected String title;
protected String genre;
protected String type;
protected double price;
protected String startTimeDate;
protected String endTimeDate;
public Stream (String listUsername, String title, String genre, String type, double price, String startTimeDate, String endTimeDate) {
this.listUsername = listUsername;
this.title = title;
this.genre = genre;
this.type = type;
this.price = price;
this.startTimeDate = startTimeDate;
this.endTimeDate = endTimeDate;
}
String genreArray[] = {"Comedy", "Lifestyle", "Music"};
String typeArray[] = {"Entertainment", "Familiy", "Work"};
public String getListUsername() { return listUsername; }
public void setListUsername(String listUsername) { this.listUsername = listUsername; }
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getStartTimeDate() {
return startTimeDate;
}
public void setStartTimeDate(String startTimeDate) {
this.startTimeDate = startTimeDate;
}
public String getEndTimeDate() { return endTimeDate; }
public void setEndTimeDate(String endTimeDate) { this.endTimeDate = endTimeDate;}
}
List block:
I think that the main issues are here, but I just can't figure out what is wrong.
package com.company;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class List extends Stream {
public List(String listUsername, String title, String genre, String type, double price, String startTimeDate, String endTimeDate) {
super(listUsername, title, genre, type, price, startTimeDate, endTimeDate);
}
ArrayList<Stream> joinableList = new ArrayList<Stream>();
ArrayList<Stream> completedList = new ArrayList<Stream>();
public void addJoinableList(Stream stream) {
joinableList.add(stream);
}
public void printJoinableList() {
for (Stream s : joinableList) {
System.out.print("\nUsername: " + s.getListUsername());
System.out.print("\nTitle: " + s.getTitle());
System.out.print("\nGenre: " + s.getGenre());
System.out.print("\nType: " + s.getType());
System.out.print("\nPrice: " + s.getPrice());
System.out.print("\nStart time and date: " + s.getStartTimeDate());
System.out.print("\nEnd time and date: " + s.getEndTimeDate() + "\n");
}
}
}
All help is appreciated, thank you.
When I see object created once like this:
User user = new User(null, null, null, null, null);
And then, no new User, I understand that you never create new instance of your object.
The rest of the code is in the same vein: you are (almost) creating only one instance of an object, rather than a new instance.
Therefore, when you change a property of said instance, it affect all objects.
You need to add somewhere in your code, when you feel that with the data entered by the user (and read by the Scanner), you may create a new User, Stream, ...
For example, after this:
list.addJoinableList(stream);
Do:
stream = new Stream(....);

Java Obtaining the First Element and Then Removing that First Element Printing the Rest of the Elements

Here is my code:
import java.util.LinkedList;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.*;
class Customer {
public String lastName;
public String firstName;
public Customer() {
}
public Customer(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer extends Customer {
public double hourlyRate;
public HourlyCustomer(String last, String first) {
super(last, first);
}
}
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty()
{
return list == null;
}
public E removeFirst(){
return list.removeFirst();
}
public E getFirst(){
return list.getFirst();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args){
while(true){
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
do{
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try{
choice = sc.nextInt();
switch(choice){
case 1:
do{
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
System.out.println("\nDo you still want to enqueue?<1> or do you want to view all in queue?<0> or \nBack to main menu for dequeueing?<menu>: ");
choice = sc.nextInt();
}while (choice != 0);
System.out.println("\nThe customers' names are: \n");
while (empList.hasItems()) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
// int choose;
// do{
//
//
// System.out.println("\nGo back to main?<1=Yes/0=No>: \n");
// choose = sc.nextInt();
// }while (choose != 1);
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e){
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
}while(choice != 0);
}
}
}
Case 2 shows no error but when I run it on the IDE it shows:
Exception in thread "main" java.util.NoSuchElementException at
java.util.LinkedList.getFirst(Unknown Source) at
GenQueue.getFirst(something.java:44) at
something.main(something.java:113)
Any idea why this happen? and how to fix it? Your help will be very much appreciated, from python I just went Java today, newbie here.
NoSuchElementException is thrown by LinkedList.getFirst when the list is empty.
You should handle that particular case before calling that method, for example:
if (!empList.hasItems()) {
System.out.println("The queue is empty!");
} else {
System.out.println("First in queue: " +empList.getFirst());
... // rest of code
}

possible already open file error; halted

So, when I run this, I get no exceptions, but the execution halts. I entered a few lines of code to see where the hault is coming from. On initial execution, it creates a file in the path given in the Customer class. Once I do one of the actions, it doesn't let me go past the first debugging line. Ideas?
Heres the application:
package javaapplication18.pkg3;
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication183 {
/**
* #param args the command line arguments
*/
static boolean keepGoing = true;
public static void main(String[] args) {
System.out.println("Welcome to the Customer Maintenance application");
//keepGoing = true;
Scanner sc = new Scanner(System.in);
while (keepGoing){
displayMenu();
String userChoice = getRequiredString("Enter a command: ", sc);
System.out.println("DEBUG LINE 1");
CustomerTextFile textFile = new CustomerTextFile();
System.out.println("DEBUG LINE 2");
performAction(userChoice, textFile);
System.out.println("DEBUG LINE 3");
}
// TODO code application logic here
}
public static void displayMenu() {
System.out.println();
System.out.println("COMMAND MENU");
System.out.println("list - List all customers");
System.out.println("add - Add a customer");
System.out.println("del - Delete a customer");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application");
System.out.println();
}
public static void performAction(String choice, CustomerTextFile textFile){
Scanner sc = new Scanner(System.in);
switch (choice.toLowerCase()) {
case "list":
//action
ArrayList<Customer> currentList = textFile.getCustomers();
for (Customer c : currentList) {
System.out.print(c.getEmail() + "\t");
System.out.print(c.getFirstName() + "\t");
System.out.println(c.getLastName());
}
break;
case "add":
String email = getRequiredString("Enter customer email address:", sc);
String firstName = getRequiredString("Enter first name:", sc);
String lastName = getRequiredString("Enter last name:", sc);
Customer c = new Customer(email, firstName, lastName);
textFile.addCustomer(c);
System.out.println(firstName + lastName + " was added to the database.");
break;
case "del":
String deleteUserByEmail = getRequiredString("Enter customer email to delete:", sc);
Customer delCustomer = textFile.getCustomer(deleteUserByEmail);
textFile.deleteCustomer(delCustomer);
break;
case "help":
//displayMenu();
break;
case "exit":
keepGoing = false;//exit();
break;
default:
System.out.println("You entereed something not in the list. Please try again.");
System.out.println();
}
}
public static boolean exit(){
System.out.println("Exit");
return false;
}
public static String getRequiredString(String prompt, Scanner sc) {
String s = "";
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
s = sc.nextLine();
if (s.equals(""))
System.out.println("Error! This entry is required. Try again.");
else
isValid = true;
}
return s;
}
}
Here is the CustomerTextFile class:
package javaapplication18.pkg3;
import java.io.*;
import java.nio.file.*;
import java.util.ArrayList;
public class CustomerTextFile implements CustomerDAO{
private ArrayList<Customer> customers = null;
private Path customersPath = null;
private File customersFile = null;
public CustomerTextFile(){
customersPath = Paths.get("customers.txt");
customersFile = customersPath.toFile();
customers = this.getCustomers();
}
#Override
public Customer getCustomer(String emailAddress) {
for (Customer c : customers) {
if (c.getEmail().equals(emailAddress))
return c;
}
return null;
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public ArrayList<Customer> getCustomers() {
if (customers != null)
return customers;
customers = new ArrayList<>();
if (!Files.exists(customersPath)) {
try {
Files.createFile(customersPath);
}
catch (IOException e) {
return null;
}
}
if (Files.exists(customersPath)) {
try (BufferedReader in = new BufferedReader(new FileReader(customersFile))){
String line = in.readLine();
while(line != null) {
String[] columns = line.split("\t");
String email = columns[0];
String firstName = columns[1];
String lastName = columns[2];
Customer c = new Customer(email, firstName, lastName);
customers.add(c);
}
}
catch (IOException e) {
System.out.println(e);
return null;
}
}
return customers;
}
#Override
public boolean addCustomer(Customer c) {
customers.add(c);
return this.saveCustomers();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public boolean updateCustomer(Customer c) {
Customer oldCustomer = this.getCustomer(c.getEmail());
int i = customers.indexOf(oldCustomer);
customers.remove(i);
customers.add(i, c);
return this.saveCustomers();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public boolean deleteCustomer(Customer c) {
customers.remove(c);
return this.saveCustomers();
}
private boolean saveCustomers() {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(customersFile)))){
for (Customer customer : customers) {
out.print(customer.getEmail() + "\t");
out.print(customer.getFirstName() + "\t");
out.println(customer.getLastName());
}
out.close();
return true;
}
catch (IOException e) {
return false;
}
}
}
Im not certain if the problem is in the application or if it is in the textfile class
run:
Welcome to the Customer Maintenance application
COMMAND MENU
list - List all customers
add - Add a customer
del - Delete a customer
help - Show this menu
exit - Exit this application
list
DEBUG LINE 1
Above was an example of the console output.
Why are you declaring a string inside the loop?
try this instead:
Scanner sc = new Scanner(System.in);
String userChoice;
do {
displayMenu();
userChoice = sc.nextLine(); //takes in the entire lien you type in
System.out.println("DEBUG LINE 1");
CustomerTextFile textFile = new CustomerTextFile();
System.out.println("DEBUG LINE 2");
performAction(userChoice, textFile);
System.out.println("DEBUG LINE 3");
} while(keepGoing);
Hope this helps

NullPointException in Simple Program, Cannot Find Fix

This is the exception I am getting:
Exception in thread "main" java.lang.NullPointerException
at BankAccountDemo.DisplayAccountFees(BankAccountDemo.java:91)
at BankAccountDemo.main(BankAccountDemo.java:30)
I am also getting this exception whenever I try to print or view all the accounts with the fees assessed.
Here is my driver program. It has 5 classes, which are also below. One of them is an abstract class with 3 descendants.
DRIVER
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class BankAccountDemo
{
public static void main(String[] args)
{
while(true) {
Scanner keyboard = new Scanner(System.in);
System.out.println("=========Menu========");
System.out.println("1. Add an account.");
System.out.println("2. To print the names of all accounts together with the fees assessed");
System.out.println("3. To print all accounts together with owner information");
System.out.println("4. To exit program");
System.out.println("Your choice: ");
int input = keyboard.nextInt();
switch(input)
{
case 1:
InputAccount();
break;
case 2:
DisplayAccountFees();
break;
case 3:
ShowAccount();
break;
default:
PrintToFile();
System.exit(0);
}
}
}
private static void InputAccount()
{
System.out.println("Please enter user data as prompted...");
System.out.println("Please enter account type: Press '1' for Checking, '2' for Savings, '3' for Loan");
System.out.println("Account Type: ");
Scanner keyboard = new Scanner(System.in);
int type = keyboard.nextInt();
switch(type)
{
case 1:
{
Checking aChecking = new Checking();
aChecking.AddAccount();
checkAccounts.add(aChecking);
break;
}
case 2:
{
Savings aSavings = new Savings();
aSavings.AddAccount();
savingsAccounts.add(aSavings);
break;
}
case 3:
{
Loan aLoan = new Loan();
aLoan.AddAccount();
loanAccounts.add(aLoan);
break;
}
}
}
private static void DisplayAccountFees()
{
for (int n=0; n < savingsAccounts.size(); n++)
{
Savings aSavings = savingsAccounts.get(n);
Person aPerson = aSavings.getAccountHolder();
System.out.println("Total Fees for: " +aPerson.getPersonName());
System.out.println("with the account number: " +aSavings.getAcctNumber());
System.out.println("are: " + aSavings.accountFee());
}
for (int n=0; n < checkAccounts.size(); n++)
{
Checking aChecking = checkAccounts.get(n);
Person aPerson = aChecking.getAccountHolder();
System.out.println("Total Fees for: " +aPerson.getPersonName());
System.out.println("with the account number: " +aChecking.getAcctNumber());
System.out.println("are: " + aChecking.accountFee());
}
for(int n=0; n < loanAccounts.size(); n++)
{
Loan aLoan = loanAccounts.get(n);
Person aPerson = aLoan.getAccountHolder();
System.out.println("Total Fees for: " +aPerson.getPersonName());
System.out.println("with the account number: " +aLoan.getAcctNumber());
System.out.println("are: " + aLoan.accountFee());
}
}
private static void ShowAccount()
{
for(int n=0; n < savingsAccounts.size(); n++)
{
Savings aSavings = savingsAccounts.get(n);
aSavings.DisplayData();
}
for(int n=0; n < checkAccounts.size(); n++)
{
Checking aChecking = checkAccounts.get(n);
aChecking.DisplayData();
}
for(int n=0; n < loanAccounts.size(); n++)
{
Loan aLoan = loanAccounts.get(n);
aLoan.DisplayData();
}
}
private static void PrintToFile()
{
try
{
FileOutputStream fileOutput = new FileOutputStream("Accounts.dat");
ObjectOutputStream printFile = new ObjectOutputStream(fileOutput);
for (int n=0; n < loanAccounts.size(); n++)
{
Loan aLoan = loanAccounts.get(n);
aLoan.PrintAccountToFile(printFile);
}
for (int n=0; n < checkAccounts.size(); n++)
{
Checking aChecking = checkAccounts.get(n);
aChecking.PrintAccountToFile(printFile);
}
for (int n=0; n < savingsAccounts.size(); n++)
{
Savings aSavings = savingsAccounts.get(n);
aSavings.PrintAccountToFile(printFile);
}
printFile.close();
fileOutput.close();
}
catch(IOException ex)
{
}
}
private static ArrayList<Checking> checkAccounts = new ArrayList<Checking>();
private static ArrayList<Savings> savingsAccounts = new ArrayList<Savings>();
private static ArrayList<Loan> loanAccounts = new ArrayList<Loan>();
}
ACCOUNT CLASS
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public abstract class Account {
private String bankName;
private String bankAddress;
private String acctNumber;
private String acctType;
private double balance;
private Person accountHolder;
public Account()
{
}
public Person setAccountHolder(Person holder)
{
return holder;
}
public void setBankName(String newBankName)
{
bankName = newBankName;
}
public void setAddress(String newBankAddress)
{
bankAddress = newBankAddress;
}
public void setAcctNumber(String newAcctNumber)
{
acctNumber = newAcctNumber;
}
public void setBalance(double newBalance)
{
balance = newBalance;
}
public void setAcctType(String newAcctType)
{
acctType = newAcctType;
}
public Person getAccountHolder()
{
return accountHolder;
}
public String getBankName()
{
return bankName;
}
public String getAddress()
{
return bankAddress;
}
public String getAcctNumber()
{
return acctNumber;
}
public String getAcctType()
{
return acctType;
}
public double getBalance()
{
return balance;
}
public abstract double accountFee();
public abstract void DisplayData();
public abstract void AddAccount();
public abstract void PrintAccountToFile(ObjectOutputStream printFile);
public void readInputAccount()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of your bank: ");
bankName = keyboard.nextLine();
System.out.println("Enter the address of your bank: ");
bankAddress = keyboard.nextLine();
System.out.println("Enter your account number: ");
acctNumber = keyboard.nextLine();
System.out.println("Enter your current balance: ");
balance = keyboard.nextDouble();
}
public void PrintBankInfo(ObjectOutputStream printFile)
{
try
{
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Bank information: ");
printFile.writeUTF("------------------------------------------");
printFile.writeUTF("Bank name: " + getBankName());
printFile.writeUTF("Bank Address: " + getAddress());
}
catch(IOException ex)
{
}
}
public void DisplayBankInfo()
{
System.out.println("------------------------------------------");
System.out.println(" Bank information: ");
System.out.println("------------------------------------------");
System.out.println("Bank name: " + getBankName());
System.out.println("Bank Address: " + getAddress());
}
}
CHECKING CLASS
import java.util.Scanner;
import java.io.*;
public class Checking extends Account {
private double monthFee;
private int checksAllowed;
private int checksUsed;
public Checking()
{
}
public double accountFee()
{
int tooManyChecks = checksUsed - checksAllowed;
double fee = monthFee + (3.00 * tooManyChecks);
return fee;
}
public double getMonthFee()
{
return monthFee;
}
public int getChecksAllowed()
{
return checksAllowed;
}
public int getChecksUsed()
{
return checksUsed;
}
public void setMonthFee(double newMonthFee)
{
monthFee = newMonthFee;
}
public void setChecksAllowed(int newChecksAllowed)
{
checksAllowed = newChecksAllowed;
}
public void setChecksUsed(int newChecksUsed)
{
checksUsed = newChecksUsed;
}
public void AddAccount()
{
Person aPerson = new Person();
aPerson.personInput();
setAccountHolder(aPerson);
readInputAccount();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the monthly fee: ");
monthFee = keyboard.nextDouble();
System.out.println("Please enter the number of free checks allowed: ");
checksAllowed = keyboard.nextInt();
System.out.println("Please enter the number of checks used: ");
checksUsed = keyboard.nextInt();
}
public void DisplayData()
{
Person aPerson = getAccountHolder();
aPerson.DisplayPersonInfo();
DisplayBankInfo();
System.out.println("------------------------------------------");
System.out.println(" Account information: ");
System.out.println("Account Type : Checking");
System.out.println("Bank account number :" + getAcctNumber());
System.out.println("Account balance :" + getBalance());
System.out.println("Monthly fee :" + getMonthFee());
System.out.println("Number of checks used :" + getChecksUsed());
System.out.println("Number of free checks :" + getChecksAllowed());
}
public void PrintAccountToFile(ObjectOutputStream printFile)
{
try
{
Person aPerson = getAccountHolder();
aPerson.PrintInfo(printFile);
PrintBankInfo(printFile);
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Account information: ");
printFile.writeUTF("Account Type : Checking");
printFile.writeUTF("Bank account number :" + getAcctNumber());
printFile.writeUTF("Account balance :" + getBalance());
printFile.writeUTF("Monthly fee :" + getMonthFee());
printFile.writeUTF("Number of checks used :" + getChecksUsed());
printFile.writeUTF("Number of free checks :" + getChecksAllowed());
printFile.writeUTF("Fees accessed : " + accountFee());
}
catch(IOException ex)
{
}
}
}
LOAN CLASS
import java.util.Scanner;
import java.io.*;
public class Loan extends Account {
private double monthPayment;
private int daysOverDue;
public Loan()
{
}
public void setMonthPayment(double newMonthPayment)
{
monthPayment = newMonthPayment;
}
public void setDaysOverDue(int newDaysOverDue)
{
daysOverDue = newDaysOverDue;
}
public double getMonthPayment()
{
return monthPayment;
}
public int getDaysOverDue()
{
return daysOverDue;
}
public double accountFee()
{
double fee = 0.001 * monthPayment * daysOverDue;
return fee;
}
public void AddAccount(){
Scanner keyboard = new Scanner(System.in);
Person aPerson = new Person();
aPerson.personInput();
setAccountHolder(aPerson);
readInputAccount();
System.out.println("Please enter the monthly payment amount: ");
monthPayment = keyboard.nextDouble();
System.out.println("Please enter the number of days past the grace period: ");
daysOverDue = keyboard.nextInt();
}
public void DisplayData()
{
Person aPerson = getAccountHolder();
aPerson.DisplayPersonInfo();
}
public void PrintAccountToFile(ObjectOutputStream printFile)
{
try
{
Person aPerson = getAccountHolder();
aPerson.PrintInfo(printFile);
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Account information: ");
printFile.writeUTF("Account Type: Loan");
printFile.writeUTF("Bank account number: " + getAcctNumber());
printFile.writeUTF("Account balance: " + getBalance());
printFile.writeUTF("Monthly payment amount: " + getMonthPayment());
printFile.writeUTF("Number of days past the grace period: " + getDaysOverDue());
printFile.writeUTF("Fees assessed: " + accountFee());
}
catch(IOException ex)
{
}
}
}
SAVINGS CLASS
import java.io.*;
import java.util.Scanner;
public class Savings extends Account {
private double minBal;
private double intRate;
private double avgBal;
public Savings()
{
}
public double accountFee()
{
double fee = 0.00;
if (avgBal < minBal)
{
fee = 50.00;
}
return fee;
}
public double getMinBal()
{
return minBal;
}
public double getIntRate()
{
return minBal;
}
public double getAvgBal()
{
return avgBal;
}
public void setMinBal(double newMinBal)
{
minBal = newMinBal;
}
public void setIntRate(double newIntRate)
{
minBal = newIntRate;
}
public double getChecks()
{
return intRate;
}
public void setChecks(double newIntRate)
{
intRate = newIntRate;
}
public void setAvgBal(double newAvgBal)
{
avgBal = newAvgBal;
}
public void AddAccount()
{
Scanner keyboard = new Scanner(System.in);
Person aPerson = new Person();
aPerson.personInput();
setAccountHolder(aPerson);
readInputAccount();
System.out.println("Please enter the minimum balance: ");
minBal = keyboard.nextDouble();
System.out.println("Please enter the average balance: ");
avgBal = keyboard.nextDouble();
System.out.println("Please enter interest rate");
intRate = keyboard.nextDouble();
}
public void DisplayData()
{
Person aPerson = getAccountHolder();
aPerson.DisplayPersonInfo();
DisplayBankInfo();
System.out.println("------------------------------------------");
System.out.println(" Account information: ");
System.out.println("Account Type: Savings Account");
System.out.println("Bank account number: " + getAcctNumber());
System.out.println("Account balance: " + getBalance());
System.out.println("Minimum balance: " + getMinBal());
System.out.println("Average balance: " + getAvgBal());
System.out.println("Interest rate: " + getIntRate());
}
public void PrintAccountToFile(ObjectOutputStream printFile)
{
try
{
Person aPerson = getAccountHolder();
aPerson.PrintInfo(printFile);
PrintBankInfo(printFile);
printFile.writeUTF("------------------------------------------");
printFile.writeUTF(" Account information: ");
printFile.writeUTF("Account Type: Savings Account");
printFile.writeUTF("Bank account number: " + getAcctNumber());
printFile.writeUTF("Account balance: " + getBalance());
printFile.writeUTF("Minimum balance: " + getMinBal());
printFile.writeUTF("Average balance: " + getAvgBal());
printFile.writeUTF("Interest rate: " + getIntRate());
printFile.writeUTF("Fees assessed: " + accountFee());
}
catch(IOException ex)
{
}
}
}
The problem is that your setAccountHolder method doesn't actually set anything:
Instead of:
public Person setAccountHolder(Person holder)
{
return holder;
}
it should be:
public void setAccountHolder(Person holder) {
this.accountHolder = holder;
}
1.) Where do you initialize savingsAccounts attribute?
2.) When you do
DisplayAccountFees()
you start by doing
Savings aSavings = savingsAccounts.get(n);
are you sure that get(n) always returns data?

Categories

Resources