gpt4 book ai didi

Java 继承 - 查找总数

转载 作者:行者123 更新时间:2023-11-30 03:03:16 25 4
gpt4 key购买 nike

我想找到付款总额,但是当我编译并运行代码时,出现此错误

Exception in thread "main" java.lang.NullPointerException.

支付类别

package tutorial3;
public class Payment {
private double amount;
public Payment()
{
this(0.0);
}
public Payment(double amount)
{
setAmount(amount);
}
public void setAmount(double amount)
{
this.amount = amount;
}

public double getAmount()
{
return amount;
}

public String toString()
{
return "amount paid is " + getAmount();
}
}
<小时/>

主类:

 public class main {
public static void main(String[] args){
Payment [] p = new Payment[2];
Scanner sales = new Scanner (System.in);
double total = 0;
for(int i=0; i<3; i++)
{
System.out.print("Sales amount? ");
double amt = sales.nextInt();
Payment cash = new Payment(amt);
}
for( Payment pv : p ){
total += pv.getAmount();
}
}
}

最佳答案

您忘记将创建的 Payment 实例分配给您的数组(此外,循环中的索引是错误的):

        for(int i=0; i<pv.length; i++)
{
System.out.print("Sales amount? ");
double amt = sales.nextDouble(); // it makes more sense to use nextDouble if
// you are storing the result in a double
pv[i] = new Payment(amt);
}

顺便说一句,我假设您的 Payment 类有一个采用 double 的构造函数,否则您的代码将无法通过编译。

关于Java 继承 - 查找总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35411203/

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