我創建了這個方法來要求用戶輸入作業詳細資訊,并保存到陣列中:
公共靜態無效 addJob() { currentJobIndex = 0;
jobs[currentJobIndex] = new Job();
jobs[currentJobIndex].getInformation();
jobs[currentJobIndex].calculateCost();
jobs[currentJobIndex].display();
jobs[currentJobIndex].getCostTotal();
currentJobIndex ;
我有這種方法來顯示保存在陣列中的所有作業:
公共靜態無效showAllJobs(){
for (Job job : jobs) {
if (job != null) {
job.display();
}
}
}
它只顯示最后輸入的作業,我不知道為什么,任何幫助將不勝感激!
uj5u.com熱心網友回復:
這是因為每次呼叫該方法時,currentJobIndex = 0;都會再次執行,因此您不會轉到陣列中的下一個位置,而是始終寫入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 ;
}
}
(旁注:由于您可能不知道會提前存盤多少作業,因此此處的串列將是更好的選擇。)
uj5u.com熱心網友回復:
這是因為添加新作業時 currentJobIndex 不會增加。
您可以通過添加以下內容來解決此問題:
public static void addJob() { currentJobIndex = 0;
jobs[currentJobIndex] = new Job();
jobs[currentJobIndex].getInformation();
jobs[currentJobIndex].calculateCost();
jobs[currentJobIndex].display();
jobs[currentJobIndex].getCostTotal();
currentJobIndex ;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/422247.html
標籤:
下一篇:如何用杰克遜序列化這個json?
