我目前正在一個程序和任何時候我打電話產品[1]沒有空指針錯誤,但當我打電話產品[0]或產品[2]我得到一個空指針錯誤。但是,我仍然得到2個不同的輸出,就像陣列中有[0]和1或1和2一樣。這裏是我的代碼空指針,對我沒有意義嗎?
FileReader file = new FileReader(location);
BufferedReader reader = new BufferedReader(file);
int numberOfLines = readLines();
String [] data = new String[numberOfLines];
Products = new Product[numberOfLines];
calc = new Calculator();
int prod_count = 0;
for(int i = 0; i < numberOfLines; i++)
{
data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
if(data[i].contains("input"))
{
continue;
}
Products[prod_count] = new Product();
Products[prod_count].setName(data[1]);
System.out.println(Products[prod_count].getName());
BigDecimal price = new BigDecimal(data[2]);
Products[prod_count].setPrice(price);
for(String dataSt : data)
{
if(dataSt.toLowerCase().contains("imported"))
{
Products[prod_count].setImported(true);
}
else{
Products[prod_count].setImported(false);
}
}
calc.calculateTax(Products[prod_count]);
calc.calculateItemTotal(Products[prod_count]);
prod_count++;
這是輸出:
imported box of chocolates
1.50
11.50
imported bottle of perfume
7.12
54.62
這版畫作品System.out.println(Products[1].getProductTotal());
這將成爲一個空指針System.out.println(Products[2].getProductTotal());
這也成爲一個空指針System.out.println(Products[0].getProductTotal());
了什麼價值'readlines方法()'返回? –
我強烈建議你學會使用調試器。 –
readLines()返回一個int值,表示文件中有多少行 – user2786754