How to remove chosen variable from array list? - java

This is a program which stores employee's information (salary, names, ID#, date hired) in an array list. When called upon (after pressing 'listButton') it lists this information in a Field for employer to look at. The employee needs to remove an employee from the list, there is a removeButton, so what would allow the employer to delete a name from the list of employees?
public class EmployeeView extends FrameView {
class Company {
String ID, firstName, lastName, annualSal, startDate, mileage;
Company (String _ID, String _firstName,String _lastName, String _annualSal, String _startDate) {
ID = _ID;
firstName = _firstName;
lastName = _lastName;
annualSal = _annualSal;
startDate = _startDate;
}
}
/** Define the ArrayList */
ArrayList <Company> employee = new ArrayList <Company>();
String ID, firstName, lastName, annualSal, startDate;
public EmployeeView(SingleFrameApplication app) {
//GUI stuff...
}
private void AddActionPerformed(java.awt.event.ActionEvent evt) {
ID = IDField.getText();
firstName = firstNameField.getText();
lastName = lastNameField.getText();
annualSal = annualSalField.getText();
startDate = startDateField.getText();
Company c = new Company(ID, firstName, lastName, annualSal, startDate);
employee.add(c);
}
private void ListActionPerformed(java.awt.event.ActionEvent evt) {
String temp = "";
for (int x=0; x<=employee.size()-1; x++) {
temp = temp + employee.get(x).ID + " "
+ employee.get(x).firstName + " "
+ employee.get(x).lastName + " "
+ employee.get(x).annualSal + " "
+ employee.get(x).startDate + "\n";
}
employeeTArea.setText(temp);
}
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
//My attempt... it didn't do anything though
int remove = 0;
for (int j = 0; j < employee.size()-1; j++) {
if (remove == Integer.parseInt(IDField.getText())) {
employee.remove(j);
}
}
}

You are initializing remove=0, what you want to do is:
for (int j = 0; j < employee.size()-1; j++) {
if (j == Integer.parseInt(IDField.getText())) {
employee.RemoveAt(j);
}
}
You don't need a remove variable. This is providing that IDField.getText() is the index of the employee you want to remove from the ArrayList

You can eliminate the for loop and just do employee.remove(company).

Related

How to organise alphabetically an array of objects in Java

I am trying to simulate a library of Albums. But I would also be able to organise the contents of the library alphabetically by the author's name. Any help in how to organise the contents of the array of objects alphabetically?
I have created a Class called Album, which I use to create my objects
public class Album {
private String author;
private String name;
private String year;
public Album(String a, String n, String y) { // constructor
author = a;
name = n;
year = y;
}
public String toString()
{
return author +","+ name + "," + year;
}
}
The class Collection is used to store the objects into an array
public class AlbumCollection {
public Album collection[]= new Album[10];
private int numAlbums = 0;
public void add (Album a){
if (numAlbums >= collection.length){
Album newcollection[]= new Album [collection.length * 2];
for (int n = 0; n < numAlbums; n ++){
newcollection[n] = collection[n];
}
newcollection = collection;
}
collection[numAlbums] = a;
numAlbums = numAlbums + 1;
}
public String toString()
{
String details = "";
for ( int p = 0; p < collection.length ; p ++)
{
details = details + collection[p] + "\n" ;
}
details += "\n";
return details;
}
}
This is the class that I am using to create the Album Objects
public class TestCollection {
public static void main(String[] args) {
AlbumCollection c = new AlbumCollection();
c.add( new Album("DaftPunk","Discovery","2001"));
c.add( new Album ("Pink Floid","The Dark Side Of The Moon","1973"));
c.add( new Album( "The Clash", "London Calling", "1979"));
System.out.print(c);
}
}
I had to change the compareTo method to sort by the author.
public class Album {
private String author;
private String name;
private String year;
public Album(String a, String n, String y) { // constructor
author = a;
name = n;
year = y;
}
public String toString()
{
return author +","+ name + "," + year;
}
public int compareTo(Album a) {
// usually toString should not be used,
// instead one of the attributes or more in a comparator chain
return author.compareTo(a.author);
}
}
And i added method sort to sorting elements of array:
public class Collection {
public Album collection[]= new Album[10];
private int numAlbums = 0;
public void Add (Album a){
if (numAlbums >= collection.length){
Album newcollection[]= new Album [collection.length * 2];
for (int n = 0; n < numAlbums; n ++){
newcollection[n] = collection[n];
}
newcollection = collection;
}
collection[numAlbums] = a;
numAlbums = numAlbums + 1;
}
public String toString()
{
String details = "";
for ( int p = 0; p < numAlbums ; p ++)
{
details = details + collection[p] + "\n" ;
}
details += "\n";
return details;
}
public void sort(){
for(int i=0;i<numAlbums;i++){
for(int j=i;j<numAlbums-1;j++){
if(collection[j].compareTo(collection[j+1])>0){
Album tmp =collection[j];
collection[j]=collection[j+1];
collection[j+1]=tmp;
}
}
}
}
}
You can not use the length of an array, if you store the number of authors, because you will print null values
public static void main(String[] args) {
Collection c = new Collection();
c.Add( new Album("DaftPunk","Discovery","2001"));
c.Add( new Album ("Pink Floid","The Dark Side Of The Moon","1973"));
c.Add( new Album( "The Clash", "London Calling", "1979"));
c.sort();
System.out.print(c);
}

Phone Book (Java) Task: Print all matches if only last name is entered

I'm creating a phone book for an assignment and I'm stuck on this part. I need to print every match if the user didn't enter the first name. Currently, my program only print the first match.
Part of the instruction: If the user enters just the last name, the program goes through the entire array, printing out every match. If the user enters both first and last names, the program will print out the first match, then stop.
This is my search method in my PhoneBook class:
// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry search(String fName, String lName) {
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName)) {
if (phoneBook[j].firstName.equals(fName) || fName.equals("")) {
return phoneBook[j];
}
}
}
return null;
}
And this is my loop for prompting the user and printing the information in my Tester
do {
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());
// if found, print out the entry
if (entry != null) {
System.out.println(entry.firstName + " " + entry.lastName + ": " + entry.phone);
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
I just need to get the program to print all of the matches if only last name is entered. I'm new to arrays and I only know Java.
Thank you in advance! :)
Update
Thanks to #TyeolRik, I was able to do "something" about it. His way was using the cases way and sorry but I do not know how to do cases. I implemented his way into mine, but I do not know how to connect them between classes. I tried to put "return resultList" on the search method, but it didn't allowed me to because it is a PhoneEntry[] instead of PhoneEntry, and that is true, but I can't search it using "entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());" if it is an array type. I need help! Thank you guys.
This is my complete current code (I have 3 classes):
PhoneBook (ignore the add method because that is for something else that I'm doing for another instruction):
public class PhoneBook {
PhoneEntry[] phoneBook;
PhoneEntry[] resultList = new PhoneEntry[10];
// constructor
public PhoneBook() {
phoneBook = new PhoneEntry[10];
// load the phone book with data
phoneBook[0] = new PhoneEntry("James", "Barclay", "(418) 665-1223");
phoneBook[1] = new PhoneEntry("Grace", "Dunbar", "(860) 399-3044");
phoneBook[2] = new PhoneEntry("Paul", "Kratides", "(815) 439-9271");
phoneBook[3] = new PhoneEntry("Violet", "Smith", "(312) 223-1937");
phoneBook[4] = new PhoneEntry("John", "Wood", "(913) 883-2874");
phoneBook[5] = new PhoneEntry("John", "Smith", "(407) 123-4555");
}
// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry search(String fName, String lName) {
int i = 0;
if (fName.equals("")) {
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
else {
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstName.equals(fName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
return null;
}
public void add(String fName, String lName, String phone) {
for (int i = 0; i < phoneBook.length; i++) {
if (phoneBook[i] == null) {
phoneBook[i] = new PhoneEntry(fName, lName, phone);
}
else {
System.out.println("No room in phone book.");
}
}
}
}
Tester:
import java.util.*;
public class PhoneBookTester {
public static void main(String[] args) {
PhoneBook pb = new PhoneBook();
PhoneEntry entry;
// Create a new scanner object
Scanner input = new Scanner(System.in);
String lastName;
String firstName;
do {
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());
// if found, print out the entry
if (entry != null) {
//for(Phonebook eachEntry : pb.search(firstName.toUpperCase(), lastName.toUpperCase())) {
System.out.println(entry.firstName + " " + entry.lastName + ": " + entry.phone);
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
}
}
PhoneEntry:
public class PhoneEntry {
String firstName; // first name of a person
String lastName; // first name of a person
String phone; // phone number of a person
// constructor
public PhoneEntry(String fName, String lName, String p) {
firstName = fName.toUpperCase();
lastName = lName.toUpperCase();
phone = p;
}
}
Solution
public PhoneEntry search(String fName, String lName) {
// There could be 2 cases.
// 1. There is only LastName == There is no First name
// 2. There are First and Last name; == There is First name
// That means, you can easily handle this problem with checking whether there is first name
int caseNumber = 0; // Default number 0 will return null
if(fName.equals("")) { // if there is no first name
caseNumber = 1;
} else {
caseNumber = 2;
}
PhoneBook[] searchResultList = new PhoneBook[]; // This will be result phonebook
switch(caseNumber) {
case 1:
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName)) {
searchResultList.add(phoneBook[j]);
}
}
return searchResultList;
case 2:
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstname.equals(fName)) {
searchResultList.add(phoneBook[j]); // This could be mutiple. (There is possible situation that there is two person whose name is same and different phone number)
}
}
return searchResultList;
default:
return null;
}
}
And you can print the answer
for(Phonebook eachBook : pb.search(inputFName, inputLName)) {
System.out.println(eachBook .firstName + " " + eachBook .lastName + ": " + eachBook .phone);
}
I don't know what exactly PhoneBook class is. So, I assume PhoneBook class has 3 variable, firstName, lastName, phone. So, please modify this answer that this codes fit your codes.
=========== Edit :: Add solution ===========
main() class
public static void main(String[] args) {
// Create a new scanner object
Scanner input = new Scanner(System.in);
String lastName;
String firstName;
int variableForCountArray;
do {
PhoneBook pb = new PhoneBook();
PhoneEntry[] entry;
entry = null;
variableForCountArray = 0;
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());
// if found, print out the entry
if (entry != null) {
for(int i = 0; i < entry.length; i++) {
if(entry[i] != null) { // Could get NullPointerException
variableForCountArray++;
}
}
for(int index = 0; index < variableForCountArray; index++) {
System.out.println(entry[index].firstName + " " + entry[index].lastName + ": " + entry[index].phone);
}
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
}
PhoneEntry.java // No change
public class PhoneEntry {
String firstName; // first name of a person
String lastName; // last name of a person
String phone; // phone number of a person
// constructor
public PhoneEntry(String fName, String lName, String p) {
firstName = fName.toUpperCase();
lastName = lName.toUpperCase();
phone = p;
}
}
PhoneBook.java
public class PhoneBook {
PhoneEntry[] phoneBook;
PhoneEntry[] resultList = new PhoneEntry[10];
// constructor
public PhoneBook() {
phoneBook = new PhoneEntry[10];
// load the phone book with data
phoneBook[0] = new PhoneEntry("James", "Barclay", "(418) 665-1223");
phoneBook[1] = new PhoneEntry("Grace", "Dunbar", "(860) 399-3044");
phoneBook[2] = new PhoneEntry("Paul", "Kratides", "(815) 439-9271");
phoneBook[3] = new PhoneEntry("Violet", "Smith", "(312) 223-1937");
phoneBook[4] = new PhoneEntry("John", "Wood", "(913) 883-2874");
phoneBook[5] = new PhoneEntry("John", "Smith", "(407) 123-4555");
}
// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry[] search(String fName, String lName) {
int i = 0;
if (fName.equals("")) {
for (int j = 0; j < phoneBook.length; j++) {
if(phoneBook[j] != null) {
if (phoneBook[j].lastName.equals(lName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
} else {
for (int j = 0; j < phoneBook.length; j++) {
if(phoneBook[j] != null) {
if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstName.equals(fName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
}
if(i == 0) {
return null;
} else {
return resultList;
}
}
public void add(String fName, String lName, String phone) {
for (int i = 0; i < phoneBook.length; i++) {
if (phoneBook[i] == null) {
phoneBook[i] = new PhoneEntry(fName, lName, phone);
}
else {
System.out.println("No room in phone book.");
}
}
}
}
Print test result
Pleast enter the last name to search: smith
Please enter the first name to search:
VIOLET SMITH: (312) 223-1937
JOHN SMITH: (407) 123-4555
Pleast enter the last name to search: smith
Please enter the first name to search: john
JOHN SMITH: (407) 123-4555
Pleast enter the last name to search: hello
Please enter the first name to search:
Name not found.
Pleast enter the last name to search: quit
Please enter the first name to search:
Good Bye!
Java8 approach.
PhoneEntry class:
public class PhoneEntry {
final String firstName;
final String lastName;
final String phone;
public PhoneEntry(String firstName, String lastName, String phone){
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
}
PhoneBook class:
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class PhoneBook {
List<PhoneEntry> contancts = new ArrayList<PhoneEntry>();
public List<PhoneEntry> search(String lastName) {
return contancts.stream()
.filter(phoneEntry ->
phoneEntry.firstName.toLowerCase().equals(lastName.toLowerCase())
|| phoneEntry.lastName.toLowerCase().equals(lastName.toLowerCase()))
.collect(Collectors.toList());
}
public Optional<PhoneEntry> search(String firsName, String lastName){
return contancts.stream()
.filter(phoneEntry ->
phoneEntry.firstName.toLowerCase().equals(firsName.toLowerCase())
&& phoneEntry.lastName.toLowerCase().equals(lastName.toLowerCase()))
.findFirst();
}
}
Test class:
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
PhoneBook phoneBook = new PhoneBook();
phoneBook.contancts.add(new PhoneEntry("John","Xavier","(992)-30421-323"));
phoneBook.contancts.add(new PhoneEntry("Mary","Doser","(992)-30421-353"));
phoneBook.contancts.add(new PhoneEntry("George","Sesame","(990)-30421-353"));
phoneBook.contancts.add(new PhoneEntry("Liam","Xavier","(990)-30211-353"));
Scanner input = new Scanner(System.in);
String lastName;
String firstName;
do {
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
Optional<PhoneEntry> entry = phoneBook.search(firstName, lastName);
List<PhoneEntry> entries = phoneBook.search(lastName);
// if found, print out the entry
if (entry.isPresent() && firstName.length() !=0) {
System.out.println(entry.get().firstName + " " + entry.get().lastName + ": " + entry.get().phone);
}else if(firstName.length() == 0 && entries.size() !=0 ){
entries.forEach(e -> System.out.println(e.firstName + " " + e.lastName + ": " + e.phone));
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
}
}

How to print a certain part of an Array?

i'm in need of assistance with a small error in my code. I have a program that has 4 String Arrays that i have to combine and print in separate places using constructors. I need to write a method: Employee[] searchWithId(Employee[] list, String search) which searches for a string in the array and returns the matched string along with the other corresponding information.
For example:
searchWithId(list, "P102432"); // search the list for the given id
Output:
Searching for the id number:P102432 ...
Found the record for the id number:P102432
first name:Amber Last Name:Nogofski
Id number:P102432
Employee number:No employee number has been assigned yet!
Heres my code so far:
Employee Class:
public static class Employee {
private String firstName;
private String lastName;
private String idNumber;
private String employeeNumber;
private int employeeCount;
/**
* Constructor
*
* #param firstName first name
* #param lastName last name
* #param idNumber id number
*/
public Employee(String firstName, String lastName, String idNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.idNumber = idNumber;
employeeCount = 0;
}
/**
* Accessors here
*/
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getIdNumber() {
return idNumber;
}
public String getEmployeeNumber() {
return employeeNumber;
}
// mutators here
/**
* #param firstName first name
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* #param lastName last name
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* #param idNumber id number
*/
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
/**
* #param employeeNumber employee number
*/
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = "";
}
#Override
public String toString() {
String result = "First name: " + getFirstName() + "\nLast name: " + getLastName()
+ "\nId number: " + getIdNumber() + "\nEmployee number: ";
if (getEmployeeNumber() == null) {
return result + "No employee number has been assigned yet!\n";
}
return result + getEmployeeNumber() + "\n";
}
}
My main and other methods:
public static void main(String[] args) {
String[] firstNames = {"Fred", "John", "Amir", "James", "Bob", "Jay", "Amber"};
String[] lastNames = {"Bond", "Kates", "Memar", "White", "Marley", "Brown", "Nogofski"};
String[] idNumbers = {"R111111", "A222222", "AB11111", "KR22121", "V311133", "L242434", "P102432"};
String[] employeeNum = {"1111", "2222", "3333", "4444", "5555", "6666", "7777"};
Employee[] list = new Employee[firstNames.length];
list = listOfEmployees(firstNames, lastNames, idNumbers); // create the list of employees in one array
System.out.println("List of employees before sorting...\n");
printEmployeeList(list); //print the list of employees
System.out.println(); // new line
searchWithId(list, "P102432"); // search the list for the given id
searchWithLastName(list, "Bond"); // search the list for the given last name
System.out.println(); // new line
searchWithId(list, "P1024444"); // search the list for the given id
searchWithLastName(list, "BoNd"); // search the list for the given last name
System.out.println();// new line
sortWithFirstName(list); // sort the employee list and then call appropriate method to print it.
list = assignEmployeeNum(list, employeeNum); // assign the employee number to the employees
System.out.println("+++After adding the employee number to the list+++");// new line
printEmployeeList(list); // print the list again with the employee number
searchWithEmployeeNum(list, "5555"); // search the list for the given employee number
sortWithFirstName(list); // sort the employee list and then call appropriate method to print it.
}
public static Employee[] listOfEmployees(String[] firstName, String[] lastName, String[] idNumber) {
Employee[] list = new Employee[firstName.length];
for (int i = 0; i < list.length; i++) {
list[i] = new Employee(firstName[i], lastName[i], idNumber[i]);
}
return list;
}
public static void printEmployeeList(Employee[] list) {
Arrays.stream(list).forEach(System.out::println);
}
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
for (int i = 0; i < list.length; i++) {
if (list[i].getIdNumber().equals(search)) {
System.out.println("Found id number: " + search);
//Arrays.toString(list); <- my try
}
}
return list;
}
You can do it as follows:
import java.util.Arrays;
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
Employee[] filteredEmployees = new Employee[list.length];
int index = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].getIdNumber().equalsIgnoreCase(search)) {
filteredEmployees[index++] = list[i];
}
}
// It'll remove the null values:
return Arrays.copyOfRange(filteredEmployees, 0, index);
}
Java 8 Version:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
return Arrays.asList(list)
.stream()
.filter(e -> e.idNumber.equalsIgnoreCase(search))
.collect(Collectors.toList())
.toArray(new Employee[list.length]);
}
change your searchWithId method to mine:
first way is using ArrayList of Employees
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
ArrayList<Employee> search_result = new ArrayList<>();
for (Employee employee : list) {
if (employee.getIdNumber().equals(search)) {
search_result.add(employee);
}
}
return search_result.toArray(new Employee[search_result.size()]);
}
or you can use array of employee to do this
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
Employee search_result[] = new Employee[list.length];
int index = 0;
for (Employee employee : list) {
if (employee.getIdNumber().equals(search)) {
search_result[index] = employee;
index++;
}
}
return Arrays.copyOfRange(search_result, 0, index);
}
even you can use
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
Employee first_search_result[] = new Employee[list.length];
int index = 0;
for (Employee employee : list) {
if (employee.getIdNumber().equals(search)) {
first_search_result[index] = employee;
index++;
}
}
Employee final_search_result[] = new Employee[index];
for (int i=0; i<first_search_result.length;i++) {
if (first_search_result[i].getIdNumber().equals(search)) {
final_search_result[i] = first_search_result[i];
}
}
return final_search_result;
}
and return final_search_result, to avoid using Arrays.copyOfRange
the above method in any way will return list of all employees with search id

How to generate a sequential account number?

I am making a bank account program and for my constructor I want it to add the customers name(which it does) and I also want it to automatically generate an account number for each customer added starting from 1 to n customers(which it does NOT do...), if I have 3 names it prints the num 3 for each of their accNum when I add these names to an ArrayList in my "BankDataBase" class.
public class Customer
{
private final String fname;
private final String lname;
Customer(String fn, String ln)
{
fname = fn;
lname = ln;
}
public class Account
{
private Customer cust;
private int accNum = 0;
private double balance;
Account(Customer c)
{
cust = c;
balance = 0;
accNum++;
}
public class DataBase
{
private Account accCust;
int getAcc = 0;
ArrayList<Account> chaseAccts = new ArrayList<>();
public void addAcct(Account me)
{
accCust = me;
chaseAccts.add(me);
}
public void display()
{
for (int i = 0; i < chaseAccts.size(); i++)
{
System.out.println(chaseAccts.get(i).getAccount() + " " + accCust.getAccNum());
}
}
Thanks in advance.
You could track the assigned account numbers statically, and assign the new account the next number in the series. Something like
public class Account
{
private static int nextAccoutNumber = 0;
private Customer cust;
private double balance;
Account(Customer c)
{
cust = c;
balance = 0;
accNum = ++nextAccountNumber;
}
}
You're adding the new account to the list, but you're also storing it in a local variable. Where you're doing this:
System.out.println(chaseAccts.get(i).getAccount() + " " + accCust.getAccNum())
you are writing out the accNum value of the same accCust each time. You need to write
System.out.println(chaseAccts.get(i).getAccount() + " " + chaseAccts.get(i).getAccNum());
And since you're using a list of type ArrayList<Account> you could just write the whole loop as:
public void display()
{
for(Account account : chaseAccts) {
System.out.println(account.getAccount() + " " + account.getAccNum());
}
}
You could try to make a static variable
private static int accSeq = 0
private Customer cust;
private int accNum = 0;
private double balance;
Account(Customer C) {
cust = c;
balance = 0;
accNum = ++accSeq;
}

Java Noob Creating a custom method to print array and calculate a duration

I have used this site to help me on many of my programming assignments before but I can not find anything similar to the issue that I am having now.
I am trying to first print the myHobbies array in the toString of the person class using the method printHobby, as well as calculate the total duration the the user has been doing the Hobby in printDuration. I am not sure why I can not get it to work and have been struggling with it for a while.
Any help would be appreciated. Here are my classes. This is my first time posting so if I am doing something wrong, please let me know.
//--------------------Person--------------------
public class Person {
String fName;
String lName;
String address;
int age;
String hobbyText;
private double durationH = 0;
private double totalDuration = 0;
Person(String f, String l, String a, int ag) {
fName = f;
lName = l;
address = a;
age = ag;
}
static Hobby[] myHobbies = new Hobby[5];
static int i = 0;
public static void setHobby(Hobby mh) {
myHobbies[i] = mh;
i++;
}
public String toString() {
return fName + " " + lName + " " + address + " " + age + " "
+ printDuration() + " ";
}
public double printDuration() {
for (int k = 0; k < myHobbies.length; k++)
totalDuration += myHobbies[k].getDuration();
return totalDuration;
}
public String printHobbies() {
for (int j = 0; j < myHobbies.length; j++)
hobbyText = myHobbies[j].toString();
return hobbyText;
}
}
//--------------------HobbyDriver--------------------
import java.util.Scanner;
public class HobbyDriver {
public static void main(String[] args) {
Hobby[] newHobby = {
new Hobby("Comics", "09/25/2012", "The Comic Store", 1),
new Hobby("Baseball", "09/30/2012", "Fenway Park", 3),
new Hobby("Programming", "09/212/2012", "Home", 6),
new Hobby("Board Games", "09/01/2012", "Tom's House", 3),
new Hobby("Watching Dr. Who", "09/27/2012", "Home", 1) };
String personChoice;
Scanner hobbyScan = new Scanner(System.in);
do {
String fName;
String lName;
int age;
String address;
String hobbyName;
String partDate;
String location;
double duration;
int userHobby;
String hobbyChoice;
System.out.println("What is your first name?");
fName = hobbyScan.nextLine();
System.out.println("What is your last name?");
lName = hobbyScan.nextLine();
System.out.println("What is your address?");
address = hobbyScan.nextLine();
System.out.println("What is your age?");
age = hobbyScan.nextInt();
hobbyScan.nextLine();
do {
System.out
.println("What hobbies would you like to do?\n"
+ "choose between Comics(0)\nBaseball(1)\nProgramming(2)\nBoard Games(3)\nWatching Dr.Who(4)\n"
+ "\nEnter the name of the hobby and then press enter");
userHobby = hobbyScan.nextInt();
hobbyScan.nextLine();
System.out
.println("Would you like to add another hobby? (enter yes/no)");
hobbyChoice = hobbyScan.nextLine();
Person.setHobby(newHobby[userHobby]);
} while (hobbyChoice.equals("yes"));
System.out
.println("Would you like to add another person? (enter yes/no)");
personChoice = hobbyScan.nextLine();
int i = 0;
Person[] newPerson = new Person[5];
newPerson[i] = new Person(fName, lName, address, age);
System.out.println(newPerson[i].toString());
i++;
} while (personChoice.equals("yes"));
}
}
//--------------------Hobby--------------------
public class Hobby {
private String hobbyName;
private String partDate;
private String location;
private double duration;
Hobby(String h, String p, String l, double d) {
hobbyName = h;
partDate = p;
location = l;
duration = d;
}
public String toString() {
return hobbyName + " " + partDate + " " + location + " " + duration;
}
public void setDuration(double d) {
d = duration;
}
public double getDuration() {
return duration;
}
}
the problem is the following:
public String printHobbies() {
for (int j = 0; j < myHobbies.length; j++)
hobbyText = myHobbies[j].toString();   
return hobbyText;
}
First, you overwrite your string in each loop. Write
hobbyText += myHobbies[j].toString();
Second, You will get a NPE if you don't add 5 Hobbies, because every item in the array is null at the beginning.
So you will have to check if myHobbies[j] is not null:
public String printHobbies() {
for (int j = 0; j < myHobbies.length; j++) {
if(myHobbies[j] != null) {
hobbyText += myHobbies[j].toString();
}
}
return hobbyText;
}
You also may want to have a look at Collections: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html
There are few bugs which may cause an issue in your code, it depends on current usage.
You do not reset the total duration, which means, that it returns proper result only after the first invocation. Otherwise it is multiplied by the number of invocations.
public double printDuration() {
for (int k = 0; k < myHobbies.length; k++)
totalDuration += myHobbies[k].getDuration();
return totalDuration;
}
You use the simple array with the fix size 5. It means, that if you add more than 5 hobbies, it will throw IndexOutOfBoundsException.
You call toString() method on all hobbies in the array nevertheless they were set. The arrays are initialized to null by default, which means, that if you set less than 5 hobbies, you try to call it on null which throws NullPointerException.
public String printHobbies() {
for (int j = 0; j < myHobbies.length; j++)
hobbyText += myHobbies[j].toString();
return hobbyText;
}

Categories

Resources