2 回答

TA貢獻2051條經驗 獲得超10個贊
您當前的代碼有兩個問題:
1)變量沒有被初始化。為此,您可以Sales在方法中創建對象(從andmain中刪除靜態關鍵字)。calCityTotalcalMonthlyTotal
2)一旦上述問題得到解決,你會遇到Arrayindexoutofboundsexception因為citySum有長度sales.length而你的循環calCityTotal進入sales[0].length。
將變量聲明為static并在constructor. 靜態變量應該獨立于任何實例。通讀Java:什么時候使用靜態方法才知道什么時候聲明靜態變量。如果要將變量聲明為static,則應在static塊中初始化它們(Java 中的靜態塊)。
下面的代碼將起作用:
public class Sales {
private String[] months;
private String[] cities;
private int[] citySum;
private int[] monthlySum;
private int[][] sales;
private int col;
private int row;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Sales salesObj = new Sales();
salesObj.calCityTotal();
salesObj.calMonthlyTotal();
}
public Sales() {
months = new String[]{"January", "Febuary", "March", "April",
"May", "June"};
cities = new String[]{"Chilliwack", "Kamloops", "Kelowna",
"NanaimoSurrey", "Vancouver", "Victoria"};
sales = new int[][]{{400, 500, 500, 600, 500, 600},
{600, 800, 800, 800, 900, 900},
{700, 700, 700, 900, 900, 1000},
{500, 600, 700, 800, 700, 700},
{900, 900, 900, 1000, 1100, 1100}};
citySum = new int[sales.length+1];
monthlySum = new int[sales[0].length];
}
public void calCityTotal() {
for (row = 0; row < sales.length; row++) {
for (col = 0; col < sales[0].length; col++) {
citySum[col] += sales[row][col];
}
}
}
public void calMonthlyTotal() {
for (row = 0; row < sales.length; row++) {
for (col = 0; col < sales[0].length; col++) {
monthlySum[row] += sales[row][col];
}
}
}
}

TA貢獻1875條經驗 獲得超3個贊
你得到了NullPointerException因為sales在nullline for (row = 0; row < sales.length; row++)。
即使您sales在構造函數中為變量設置了一個值Sales(),您也永遠不會調用該構造函數(如new Sales())。
因此,要解決此問題,NullPointerException您可以在方法中調用Sales構造函數,main()如下所示:
public static void main(String[] args)
{
new Sales();
calCityTotal();
calMonthlyTotal();
displayTable();
}
編輯
修復后NullPointerException,您的代碼仍然有一些其他問題。
在里面calCityTotal(),我認為sales[0].length應該更正。sales[row].length
citySum數組初始化為sales. 這意味著citySum.length等于“行”的數量。但是你寫citySum[col]了這會導致ArrayIndexOutOfBoundsException因為“列”的數量可以超過citySum.length. (這實際上發生在您的程序中。因為行數 = 5,列數 = 6。)
添加回答
舉報