0

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!

2
  • When you use the addJob() method you have currentJobIndex = 0; so items will only ever be inserted al position 0 (and will overwrite anything else that was there). You need to increment this number and ensure that your array has space. You should probably be using an ArrayList that already has an add method. Commented Jan 27, 2022 at 21:38
  • Thank you, removing the currentJobIndex = 0; resolved the issue! Commented Jan 27, 2022 at 21:42

2 Answers 2

0

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.)

Sign up to request clarification or add additional context in comments.

Comments

-1

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++;

     }

1 Comment

This will not solve the problem. currentJobIndex will still be set to 0 every time the method is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.