我目前正在开发一个程序,每当我调用 Products[1] 时,都不会出现空指针错误,但是,当我调用 Products[0] 或 Products[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());
最佳答案
您正在跳过包含“input”的行。
if(data[i].contains("input")) {
continue; // Products[i] will be null
}
也许最好将 products
制作为 ArrayList,并仅向其中添加有意义的行。
products
也应以小写字母开头,以遵循 Java 约定。类型以大写字母开头,参数和变量以小写字母开头。并非所有 Java 编码约定都是完美的——但是这个非常有用。
代码的结构很好,但是数组不是一种从程序逻辑构建的非常灵活的类型(因为长度必须预先确定,跳过需要您跟踪索引,并且它无法跟踪构建时的大小)。
一般来说你应该构建List(ArrayList)。 Map(HashMap、LinkedHashMap、TreeMap)和Set(HashSet)也很有用。
<小时/>第二个错误:正如 Bohemian 所说:在 data[]
中,您混淆了所有行列表的概念,而 data[]
是解析的标记/从单行拆分。
“数据”通常是一个无意义的术语。使用有意义的术语/名称,您的程序中出现错误的可能性就会大大降低。
您可能应该只使用 tokens
作为行标记,而不是在需要之前在外部/之前声明它,并且不要尝试按行对其进行索引 - 因为,很简单,绝对应该有没必要。
for(int i = 0; i < numberOfLines; i++) {
// we shouldn't need data[] for all lines, and we weren't using it as such.
String line = reader.readLine();
String[] tokens = line.split("(?<=\\d)\\s+|\\s+at\\s+");
//
if (tokens[0].equals("input")) { // unclear which you actually mean.
/* if (line.contains("input")) { */
continue;
}
当您提供问题的示例输入时,请将其编辑到问题正文中,以便其可读。将其放在无法正确阅读的评论中,只会浪费那些试图帮助您的人的时间。
关于java - 空指针对我来说毫无意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18939028/