繁体   English   中英

将对象保存到数组并打印存储的 object 数据

[英]Saving objects to an array and printing stored object data

我创建了这个方法来要求用户输入工作详细信息,并保存到数组中:

公共 static 无效 addJob() { currentJobIndex = 0;

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

我有这种方法来显示保存在数组中的所有作业:

公共 static 无效 showAllJobs() {

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

}

它只显示最后输入的工作,我不知道为什么,任何帮助将不胜感激!

这是因为每次调用该方法时, currentJobIndex = 0; 再次执行,因此您不要 go 到数组中的下一个 position ,但始终写入jobs[0] currentJobIndex需要是一个全局变量,如下所示:

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

(旁注:由于您可能不知道会提前存储多少作业,因此此处的列表将是更好的选择。)

这是因为添加新作业时 currentJobIndex 不会增加。

您可以通过添加以下内容来解决此问题:

public static void addJob() { currentJobIndex = 0;

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

    currentJobIndex++;

     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM