Home > Mobile >  Saving objects to an array and printing stored object data
Saving objects to an array and printing stored object data

Time:01-28

I have this method created to ask a user to input job details, and save to an array:

public static void addJob() { currentJobIndex = 0;

    jobs[currentJobIndex] = new Job();
    jobs[currentJobIndex].getInformation();
    jobs[currentJobIndex].calculateCost();
    jobs[currentJobIndex].display();
    jobs[currentJobIndex].getCostTotal();
    currentJobIndex  ;

I have this method to display all jobs saved in the array:

public static void showAllJobs() {

    for (Job job : jobs) {
        if (job != null) {
            job.display();
        }
    }

}

It is only showing the last entered job and I cant figure out why, any assistance would be appreciated!

CodePudding user response:

This is because every time you call the method, currentJobIndex = 0; is executed again, so you do not go to the next position in the array, but always write to jobs[0]. currentJobIndex needs to be a global variable, like this:

public class Job(){
   private int[] jobs = new int[5]; // Specify length of array here.
   private currentJobIndex = 0;

   public void addJob(){
    jobs[currentJobIndex] = new Job();
    jobs[currentJobIndex].getInformation();
    jobs[currentJobIndex].calculateCost();
    jobs[currentJobIndex].display();
    jobs[currentJobIndex].getCostTotal();
    currentJobIndex  ;
   }
}

(Sidenote: Since you probably don't know how many jobs will be stored in advance, a list would be the better choice here.)

CodePudding user response:

This is because currentJobIndex doesn't increment when you add a new job.

You can fix this by adding:

public static void addJob() { currentJobIndex = 0;

    jobs[currentJobIndex] = new Job();
    jobs[currentJobIndex].getInformation();
    jobs[currentJobIndex].calculateCost();
    jobs[currentJobIndex].display();
    jobs[currentJobIndex].getCostTotal();

    currentJobIndex  ;

     }
  •  Tags:  
  • Related