2 回答

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
您當(dāng)前的代碼有兩個(gè)問題:
1)變量沒有被初始化。為此,您可以Sales在方法中創(chuàng)建對(duì)象(從andmain中刪除靜態(tài)關(guān)鍵字)。calCityTotalcalMonthlyTotal
2)一旦上述問題得到解決,你會(huì)遇到Arrayindexoutofboundsexception因?yàn)閏itySum有長(zhǎng)度sales.length而你的循環(huán)calCityTotal進(jìn)入sales[0].length。
將變量聲明為static并在constructor. 靜態(tài)變量應(yīng)該獨(dú)立于任何實(shí)例。通讀Java:什么時(shí)候使用靜態(tài)方法才知道什么時(shí)候聲明靜態(tài)變量。如果要將變量聲明為static,則應(yīng)在static塊中初始化它們(Java 中的靜態(tài)塊)。
下面的代碼將起作用:
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貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊
你得到了NullPointerException因?yàn)閟ales在nullline for (row = 0; row < sales.length; row++)。
即使您sales在構(gòu)造函數(shù)中為變量設(shè)置了一個(gè)值Sales(),您也永遠(yuǎn)不會(huì)調(diào)用該構(gòu)造函數(shù)(如new Sales())。
因此,要解決此問題,NullPointerException您可以在方法中調(diào)用Sales構(gòu)造函數(shù),main()如下所示:
public static void main(String[] args)
{
new Sales();
calCityTotal();
calMonthlyTotal();
displayTable();
}
編輯
修復(fù)后NullPointerException,您的代碼仍然有一些其他問題。
在里面calCityTotal(),我認(rèn)為sales[0].length應(yīng)該更正。sales[row].length
citySum數(shù)組初始化為sales. 這意味著citySum.length等于“行”的數(shù)量。但是你寫citySum[col]了這會(huì)導(dǎo)致ArrayIndexOutOfBoundsException因?yàn)椤傲小钡臄?shù)量可以超過citySum.length. (這實(shí)際上發(fā)生在您的程序中。因?yàn)樾袛?shù) = 5,列數(shù) = 6。)
添加回答
舉報(bào)