我已经关注了nullpointerexception的相关链接,例如:
How to solve java.lang.NullPointerException error?
What is a NullPointerException, and how do I fix it?
我从代码中排除了大部分的nullpointer异常,但我无法理解跟随nullpointer异常的原因。
Exception in thread "main" java.lang.NullPointerException
at Calculate.main(Calculate.java:9)
我在调试模式下运行并看到" sc.items.add(cd)" (Calculate.java第9行);一片空白!任何人都可以解释原因。
我正在实施访客模式。我正在计算不同物品的成本。一件是CD。以下是代码:
ShoppingCart.java
import java.util.ArrayList;
public class ShoppingCart {
ArrayList<Visitable> items;
public double calculatePostage(){
//Create a visitor
PostageVisitor visitor = new PostageVisitor();
// iterate through all items
for( Visitable item: items){
item.accept(visitor);
}
double postage = visitor.getTotalPostage();
return postage;
}
}
Calculate.java
public class Calculate {
public static void main(String[] args) {
// TODO Auto-generated method stub
ShoppingCart sc = new ShoppingCart();
CD cd = new CD(100);
sc.items.add(cd);
double postageInMain = sc.calculatePostage();
System.out.println(postageInMain);
}
}
CD.java
public class CD implements Visitable {
private double price;
@Override
public void accept(Visitor visitor) {
// TODO Auto-generated method stub
}
public CD(double price){
this.price = price;
}
double getPrice(){
return price;
}
}
PostageVisitor.java
public class PostageVisitor implements Visitor {
private double totalPostageForCart;
public void visit (CD cd){
totalPostageForCart += cd.getPrice();
}
public void visit (DVD dvd){
totalPostageForCart += dvd.getPrice();
}
// return the internal state
public double getTotalPostage(){
return totalPostageForCart;
}
}
Visitable.java
public interface Visitable {
public void accept(Visitor visitor);
}
Visitor.java
public interface Visitor {
public void visit(Book book);
public void visit(CD cd);
}
答案 0 :(得分:0)
类items
中的字段ShoppingCart
未使用ArrayList
对象初始化,这就是您获得NPE的原因。
import java.util.ArrayList;
public class ShoppingCart {
ArrayList<Visitable> items = new ArrayList<>(); // <---- this will solve the problem
public double calculatePostage(){
//Create a visitor
PostageVisitor visitor = new PostageVisitor();
// iterate through all items
for( Visitable item: items){
item.accept(visitor);
}
double postage = visitor.getTotalPostage();
return postage;
}
}
另外,我想提一下,在接口方法中你真的不需要public
修饰符,它只是多余的。
答案 1 :(得分:0)
将ShoppingCart.java文件ArrayList<Visitable> items;
代码更改为
ArrayList<Visitable> items;
items = new ArrayList<>();