1

I want to find the total amount of payment, but when I compile and run the code, I get this error

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

payment class

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

main class:

 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();
            }
        }      
    }
Félix Gagnon-Grenier
  • 7,344
  • 10
  • 45
  • 58
Synetrix
  • 53
  • 2
  • 11

2 Answers2

2

You forgot to assign the created Payment instances to your array (and in addition the indices in your loop were wrong) :

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

BTW, I'm assuming your Payment class has a constructor that takes a double, or your code wouldn't pass compilation.

Eran
  • 359,724
  • 45
  • 626
  • 694
0

You have created Payment cash but it was not assigned to one of the elements of Payment object array ( Payment p[] )

Replace

 Payment cash = new Payment(amt);

with

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);
 }        
Ravindra babu
  • 42,401
  • 8
  • 208
  • 194