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;
}
Related
I have an assignment that requires me to create a method called getExamRange that looks at an array which includes the exam scores of several students, takes the lowest and highest scores, and subtracts the minimum exam score from the maximum exam score. I also have to create a getMostImprovedStudent which run the getExamRange method on an array of Students and returns the student with the highest exam range. I'm having trouble getting the correct results when the code is run. What is causing this problem?
Here is the code for the Student.java class:
import java.util.*;
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
/**
* This is a constructor. A constructor is a method
* that creates an object -- it creates an instance
* of the class. What that means is it takes the input
* parameters and sets the instance variables (or fields)
* to the proper values.
*
* Check out StudentTester.java for an example of how to use
* this constructor.
*/
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[NUM_EXAMS];
numExamsTaken = 0;
}
public int getExamRange()
{
Arrays.sort(exams);
int examScore1 = exams[0];
int examScore2 = 0;
int lastPos = 0;
for(int i = 0; i < exams.length - 1; i++)
{
lastPos++;
}
examScore2 = exams[lastPos];
return examScore2 - examScore1;
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
// This is a setter method to set the GPA for the Student.
public void setGPA(double theGPA)
{
gpa = theGPA;
}
/**
* This is a toString for the Student class. It returns a String
* representation of the object, which includes the fields
* in that object.
*/
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
and here is the code for the Classroom.java class:
public class Classroom
{
Student[] students;
int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getMostImprovedStudent()
{
int highestScore = 0;
int score = 0;
int location = 0;
int finalLocation = 0;
for(Student s: students)
{
score = s.getExamRange();
location++;
if(score > highestScore)
{
highestScore = score;
finalLocation = location;
}
}
return students[finalLocation - 1];
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
Here are the directions for the assignment which state what the methods are supposed to do:
Taking our Student and Classroom example from earlier, you should fill in the method getMostImprovedStudent, as well as the method getExamRange. The most improved student is the one with the largest exam score range.
To compute the exam score range, you must subtract the minimum exam score from the maximum exam score.
For example, if the exam scores were 90, 75, and 84, the range would be 90 - 75 = 15.
Firstly let us look at the getExamRange function
public int getExamRange(){
if(exams == null ||exams.length == 0){
return 0;
}
int min = exams[0];
int max = exams[0];
for (int i : exams
) {
if(i<min){
min=i;
}
if(i>max){
max=i;
}
}
return max - min;
}
and now on getMostImprovedStudent
public Student getMostImprovedStudent()
{
if(students == null ||students[0] == null || students.length=0){
return null;
}
int highestScore = students[0].getExamRange();
int score = 0;
Student mostImprovedStudent = students[0]
for(int i=0;i<students.length;i++)
{
if(students[i]!=null){
score = students[i].getExamRange();
if(score > highestScore)
{
highestScore = score;
mostImprovedStudent = students[i];
}
}
}
return mostImprovedStudent;
}
package chapter10;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Customer {
private String name;
private String streetAddress;
private String phoneNumber;
private int total;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress(){
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getTotal(){
return total;
}
public void setTotal(int total){
this.total = total;
}
public static void assign(){
int a = (int) (Math.random() + 10);
int r = (int) (Math.random() + 10);
int f = (int) (Math.random() + 10);
System.out.println(a + r + f + "x" + "x" + "x");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList <Customer > customerList = new ArrayList <Customer>();
char ans;
do
{
Customer customer = new Customer();
System.out.print("Customer name ");
customer.setName(in.next());
int i = 0;
++i;
System.out.print("Street Address ");
customer.setStreetAddress(in.next());
System.out.print("Phone Number ");
customer.setPhoneNumber(in.next());
customerList.add(customer);
System.out.println("Enter total sales ");
customer.setTotal(in.nextInt());
System.out.println("Would you like to enter in a new customer ( y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
((String) customerList).concat("")
} while(ans == 'y');
for(Customer c: customerList){
System.out.print(c.getName() + "\n" + "Phone number is " +c .getPhoneNumber() +"\n" + "Total sales is "+ c.getTotal() + "\n" + "Address is"+ c.getStreetAddress());
}
for(int i=0; i<customerList.size(); i++){
//System.out.print(customerList.get(i).getName());
}
}
}
I need to assign a number to each value in the arraylist but i am getting an error that says that I have to convert to string (arraylist). How do I add it?
If what I gather from the comments is correct then I believe this is what you want:
Your current assign() is incorrect if you want random values 1-10, it should look like this instead:
public String assign(){
Random rand = new Random();
int a = rand.nextInt(10) + 1;
int r = rand.nextInt(10) + 1;
int f = rand.nextInt(10) + 1;
return a+r+f+"xxx";
}
Customer will look like this:
public class Customer {
private String name;
private String customerNumber;
private String streetAddress;
private String phoneNumber;
private int total;
...
...
...
public String getCustomerNumber() { return this.customerNumber; }
public void setCustomerNumber(String cNumber) { this.customerNumber = cNumber; }
And assigning the numbers should look like this:
for(Customer c : customerList) {
c.setCustomerNumber(assign());
}
Also avoid this line of code, it's a really bad idea:
((String) customerList).concat("")
You should probably rename the customerNumber to customerID.
Hiiii
As i understand you are trying to to add number to each value to arrayList ,And same time you are creating arrayList of customer object, So first understand about arrayList of object,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Customer> al = new ArrayList();
al.add(c1);
al.add(c2);
Here this ArrayList object save only address of customer object so how can you change the address of Customer object ; You can not add number in Customer type ArrayList Object,
There is another way typecast your ArrayList to Object type and then no need to typecast again , you can add any type of object in ArrayList
like this,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Object> al = new ArrayList();
al.add(c1);
al.add(c2);
In your code there's the following line:
((String) customerList).concat("")
Trying to cast a List to a String is doomed to failure - I'm not sure why do you think it should work.
If you want a String representation of the list, you should implement a toString() method in class Customer and then you can do something like:
System.out.println(Arrays.toString(customerList.toArray()));
Instead of using ArrayList, you can use Map. In which you can have the number as key and value as Customer.
http://examples.javacodegeeks.com/java-basics/java-map-example/ Contains the example of using Map
Answer in Storing a new object as the value of a hashmap? contains info about how to use Object as value in HashMap
Is it possible to do such a thing? Say I wanted to add the values I gave values to in CountriesTest and add them to the ArrayList in Countries. Also how could I reference aCountries to print for option 2, seeing that I created it inside option 1 I can't access it anywhere else.
Here is my interface
public interface CountriesInterface
{
public String largestPop();
public String largestArea();
public String popDensity();
}
Here is the Countries class
import java.util.*;
public class Countries implements CountriesInterface
{
private final List<CountriesInterface> theCountries = new ArrayList<>();
private String cName;
private String finalPopName;
private String finalAreaName;
private String finalDensityName;
private int cPop = 0;
private int cArea = 0;
private int popDensity = 0;
private int popCounter = 0;
private int areaCounter = 0;
private int densityCounter = 0;
public Countries(String cName, int cPop, int cArea, int popDensity)
{
this.cName = cName;
this.cPop = cPop;
this.cArea = cArea;
this.popDensity = popDensity;
}
public String largestPop()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cPop > popCounter)
{
popCounter = cPop;
finalPopName = cName;
}
}
return finalPopName;
}
public String largestArea()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cArea > areaCounter)
{
areaCounter = cArea;
finalAreaName = cName;
}
}
return finalAreaName;
}
public String popDensity()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(popDensity > densityCounter)
{
densityCounter = popDensity;
finalDensityName = cName;
}
}
return finalDensityName;
}
}
Here is the CountriesTest class
import java.util.*;
public class CountriesTest
{
public static void main(String[] args)
{
int population = 0;
int area = 0;
int density = 0;
Scanner myScanner = new Scanner(System.in);
boolean done = false;
do
{
System.out.println("1. Enter a country \n2. Print countries with the largest population, area, and population density \n3. Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter name of country: ");
String input1 = myScanner.nextLine();
System.out.print("Enter area of country in square kilometers: ");
String input2 = myScanner.nextLine();
population = Integer.parseInt(input2);
System.out.print("Enter population of country: ");
String input3 = myScanner.nextLine();
area = Integer.parseInt(input3);
density = population/area;
Countries aCountries = new Countries(input1, population, area, density);
}
else if(choice == 2)
{
System.out.println("The country with the largest population: " );
System.out.println("The country with the largest area: " );
System.out.println("The country with the largest population density is: " );
}
else if(choice == 3)
{
done = true;
}
else
System.out.println("Invalid Choice");
}
while (!done);
System.exit(0);
}
}
OK, there's some mix-up in your code.
You are using the "Countries" class at the same time for an individual Country AND the list of countries. I won't recommand it, but at least you should make "static" members and methods which are for the list of countries. Or you could declare List theCountries = new ArrayList<>(); inside the main method instead.
You are never adding the new "Countries" object to the list of countries. So, if you've declared theCountries in the main method, just uste "theCountries.add(aCountries)" right after the "new Countries(...)".
your seach methods (like largestPop) won't work because they are never searching through the content of the "theCountries" ArrayList. (the "i" variable is just iterating through the indices, but never actually used to get a countent from this ArrayList).
and btw, System.exit(0) is not needed (it's implied)
I am trying to read in a figure for a brokers earnings for quarter one of the year.I want to ensure that 0 or less can not be entered but when I enter 0 it just takes it in anyway and does not throw the exception?
What am I doing wrong?Any help would be greatly appreciated.
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException("new quarter must be > 0.0");
}
Ok heres my whole assignment code
import java.util.Scanner;
public class Broker {
//(a) declare instance variables
private String department, firstName, lastName;
private double quarter1, quarter2, quarter3, quarter4;
//(b) Access methods for instance variables
public void setDepartmentName(String newName)
{
department=newName;
}
public String getDepartment ()
{
return department;
}
//set and get methods for first name
public void setFirstName (String newFirstName)
{
firstName=newFirstName;
}
public String getFirstName ()
{
return firstName;
}
//set and get methods for last name
public void setLastName(String newLastName)
{
lastName=newLastName;
}
public String getLastName ()
{
return lastName;
}
//set and get methods for Quarter 1
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException(
"new quarter must be > 0.0");
}
public double getQuarter1()
{
return quarter1;
}
//set and get methods for Quarter 2
public void setQuarter2(double newQuarter2)
{
quarter2 = newQuarter2;
}
public double getQuarter2 ()
{
return quarter2;
}
//set and get methods for Quarter 3
public void setQuarter3(double newQuarter3)
{
quarter2 = newQuarter3;
}
public double getQuarter3 ()
{
return quarter3;
}
//set and get methods for Quarter 4
public void setQuarter4(double newQuarter4)
{
quarter4 = newQuarter4;
}
public double getQuarter4 ()
{
return quarter4;
}
//(c) class variable annualbrokerage total and two access methods
private static double brokerageTotal;
public void setbrokerageTotal(double newBrokerageTotal)
{
newBrokerageTotal=brokerageTotal;
}
//(c) constructor to initialise instance variables department,firstname and lastname
public Broker (String dept, String first, String last )
{
department = dept;
firstName = first;
lastName = last;
}
// (d) constructor to initialise all instance variables from (a)
public Broker (String dept, String first, String last,double q1,double q2,double q3,double q4 )
{
department = dept;
firstName = first;
lastName = last;
quarter1 = q1;
quarter2 = q2;
quarter3 = q3;
quarter4 = q4;
}
// (e) no-argument constructor to initialise default broker instance
public Broker ()
{
department = null;
firstName = null;
lastName = null;
quarter1 = 0;
quarter2 = 0;
quarter3 = 0;
quarter4 = 0;
}
//(f) Method to read in quarters from user
public void readInQuarters ()
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt();
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
} //end of read in quarters method
// (g) getBrokerTotal Method to return total trades for 4 quarters
public double getBrokerTotal()
{
//code to calculate broker quarterly totals
double brokerTotal = quarter1 + quarter2 + quarter3 + quarter4;
return brokerTotal;
} //end of getBrokerTotal method
//(e) getBonus method to calculate brokers bonus
public double getBonus()
{
double bonusRate=0;
double bonus=0;
//bonus rate depending on department rate
if("Dublin"==department)
bonusRate=.12;
else if("London"==department)
bonusRate=.15;
else
bonusRate=.10;
bonus = (quarter1 + quarter2 + quarter3 + quarter4)*(bonusRate);
return bonus;
}
//(i) to string method for broker class
public String toString()
{
return String.format(" Name: "+ getFirstName()+"\n Surname: "+getLastName()+"\n Department: "+getDepartment()+"\n Total: "+getBrokerTotal()+"\n Bonus: "+getBonus()+"\n\n");
}//end of toString method
//(i) Static methods to read in broker array and output quarterly totals
//Quarter1 totals method
public static double getQuarter1Total (Broker[]brokerQuarter1Array)
{
double quarter1Total = brokerQuarter1Array[0].getQuarter1()+ brokerQuarter1Array[1].getQuarter1()+ brokerQuarter1Array[2].getQuarter1()+ brokerQuarter1Array[3].getQuarter1()
+ brokerQuarter1Array[4].getQuarter1() + brokerQuarter1Array[5].getQuarter1();
return quarter1Total;
}
//Quarter2 totals method
public static double getQuarter2Total (Broker[]brokerQuarter2Array)
{
double quarter2Total = brokerQuarter2Array[0].getQuarter2()+ brokerQuarter2Array[1].getQuarter2()+ brokerQuarter2Array[2].getQuarter2()+ brokerQuarter2Array[3].getQuarter2()
+ brokerQuarter2Array[4].getQuarter2() + brokerQuarter2Array[5].getQuarter2();
return quarter2Total;
}
//Quarter3 totals method
public static double getQuarter3Total (Broker[]brokerQuarter3Array)
{
double quarter3Total = brokerQuarter3Array[0].getQuarter3()+ brokerQuarter3Array[1].getQuarter3()+ brokerQuarter3Array[2].getQuarter3()+ brokerQuarter3Array[3].getQuarter3()
+ brokerQuarter3Array[4].getQuarter3() + brokerQuarter3Array[5].getQuarter3();
return quarter3Total;
}
//Quarter4 totals method
public static double getQuarter4Total (Broker[]brokerQuarter4Array)
{
double quarter4Total = brokerQuarter4Array[0].getQuarter4()+ brokerQuarter4Array[1].getQuarter4()+ brokerQuarter4Array[2].getQuarter4()+ brokerQuarter4Array[3].getQuarter4()
+ brokerQuarter4Array[4].getQuarter4() + brokerQuarter4Array[5].getQuarter4();
return quarter4Total;
}
// Static method to calculate total brokerage totals for all brokers
public static void setBrokerageTotal (Broker[] brokerTotalsArray)
{
double annualBrokerageTotal= brokerTotalsArray[0].getBrokerTotal() + brokerTotalsArray[1].getBrokerTotal()
+ brokerTotalsArray[2].getBrokerTotal() + brokerTotalsArray[3].getBrokerTotal() + brokerTotalsArray[4].getBrokerTotal() + brokerTotalsArray[5].getBrokerTotal();
}
// Static method to get the total bonuses for all brokers cobined
public static double getBrokerageBonus (Broker [] brokerageBonusTotalArray)
{
double totalBrokerageBonus = brokerageBonusTotalArray[0].getBonus()+ brokerageBonusTotalArray[1].getBonus()+ brokerageBonusTotalArray[2].getBonus()+ brokerageBonusTotalArray[3].getBonus()
+ brokerageBonusTotalArray[4].getBonus() + brokerageBonusTotalArray[5].getBonus();
return totalBrokerageBonus;
}
public static void main(String[]args)
{
//Part-B
///(a) create broker1 with the no argument constructor
Broker broker1=new Broker();
broker1.setDepartmentName("Dublin");
broker1.setFirstName("John");
broker1.setLastName("Wall");
broker1.setQuarter1(12);
broker1.setQuarter2(24);
broker1.setQuarter3(26);
broker1.setQuarter4(17);
System.out.print(broker1);
//(b) create broker2
Broker broker2 = new Broker("London","Sarah","May");
broker2.setQuarter1(8);
broker2.setQuarter2(11);
broker2.setQuarter3(7);
broker2.setQuarter4(9);
System.out.print(broker2);
//(c) create broker3
Broker broker3 = new Broker("London","Ruth","Lavin");
//call read in quarters method
broker3.readInQuarters();
System.out.print(broker3);
//(d) create broker4,broker5,broker6
Broker broker4=new Broker("Dublin","Conor","Smith",21,23,26,31);
Broker broker5=new Broker("Paris","Jerome","Duignan",14,14,17,18);
Broker broker6=new Broker("Paris","Patick","Bateman",23,24,26,35);
//(e) Create broker array
Broker[] brokers;
brokers=new Broker [6];
brokers[0]=broker1;brokers[1]=broker2;brokers[2]=broker3;brokers[3]=broker4;brokers[4]=broker5;brokers[5]=broker6;
//(f) Output second table
String[] headings ={"Dept","Firstname","Surname","Q1","Q2","Q3","Q4","Total","Bonus"};
//loop to print the headings
for (int i = 0; i < headings.length; i++)
{
System.out.print(headings[i]+" ");
}
//print a space under the headings
System.out.println(" \n");
//loop to print the main table plus format specifiers to align the text
for (int i = 0; i < 5; i++)
{
System.out.printf("%-7s %-13s %-11s %-6s %-6s %-6s %-6s %-10s %.1f \n\n",brokers[i].getDepartment(), brokers[i].getFirstName(),brokers[i].getLastName(),brokers[i].getQuarter1(),brokers[i].getQuarter2(),brokers[i].getQuarter3(),brokers[i].getQuarter4(),brokers[i].getBrokerTotal(),brokers[i].getBonus());
}
// console printout for quarterly totals
System.out.printf("%33s \n","Quarterly ");
System.out.printf("%29 %9s %6s %6s %6s %6s \n","Total ",getQuarter1Total(brokers),getQuarter2Total(brokers),getQuarter3Total(brokers),getQuarter4Total(brokers),getBrokerageBonus(brokers));
} //end of method main
} //end of class broker
er
You aren't using your setters. The problem is here
public void readInQuarters () {
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt(); // <-- Use your setters!
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
// should be,
setQuarter1(input.nextInt()); // and so on... although I will point out, you should
// be reading double(s) apparently.
}
Hello Friend I have give a suggestion which is am also use in our project
call this method before submitting the value. And if return true then update data other wise show mgs in validate method of where from call update
boolean validate() {
int c = Integer.parseInt(txtFieldSetupTopElevation.getText().toString().trim());
if (c <= 0) {
// Here use code for show msg error or information
// return true if value is greater than 0 other wise return else
return false;
}
}
Sandeep
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;
}