Java继承 - 查找总金额

时间:2016-02-15 13:54:36

标签: java

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

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();
            }
        }      
    }

2 个答案:

答案 0 :(得分:2)

您忘了将创建的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的构造函数,或者你的代码不能通过编译。

答案 1 :(得分:0)

您已创建Payment cash,但未将其分配给Payment对象数组(Payment p[])的其中一个元素

替换

 Payment cash = new Payment(amt);

p[i] = new Payment(amt);
for(int i=0; i<3; i++)
{
     System.out.print("Sales amount? ");
     double amt = sales.nextDouble(); // change int to double
     p[i] = new Payment(amt);
 }