gpt4 book ai didi

java - 在调用方法之前检查非空实际值时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 07:28:51 25 4
gpt4 key购买 nike

public class InvoiceApp 
{

public static void main(String[] args)
{
//create instances
Client c = new Client(...); //some client value
Vendor v = new Vendor(...); //some vendor value

Project p = new Project(...); //some project value

//passing in some values for invoice, with p being the project created
Invoice i = new Invoice(105, p, Calendar.getInstance(), true);


}

}

对于发票类,

    private int id;
private Project p;
private Calendar iDate;
private boolean vatApp; //is vat payable on this invoice?
private Costing c;

public Invoice(int id, Project p, Calendar iDate, boolean vatApp) {

this.id = id;
this.p= p;
this.iDate = iDate;
this.vatApp= vatApp;


c.calculateTotal(p, vatApp);

}

最后是成本计算类

private Project p;

public void calculateTotal(Project p, boolean vatA)
{
System.out.print("HELLO 2");
//actual computation formula
}

NullException 指的是 c.calculateTotal(p, vatApp);线。知道为什么会发生这种情况,即使我已经使用 System.out.println 检查过以确保在调用该方法之前这些值具有正确的值?

最佳答案

Costing 实例c 仍然未初始化(默认情况下为null)。这就是当您尝试调用其方法时会收到 NullPointerException 的原因。

private Costing c = new Costing(...); // You need to initialize this also.

关于java - 在调用方法之前检查非空实际值时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20045120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com