The Product [] car;
Int b;
Int size=0;
Public ShoppingCar () {
The car=new Product [5].
}
Public void the add (Product a) {
If (size>=car. Length) {
The car=Arrays. CopyOf (car, car. Length * 3);
}
The car [size]=a;
size++;
(this class has been defined the Product)
I put the car=new Pdoduct [5] in the add method, call the add method in the Test when the null pointer exception, but I'll be okay put this inside a constructor, is this why?
CodePudding user response:
Professional point questions, post code of your live and look good!CodePudding user response:
Well, sorry brother, for the first time use this wasn't too will use...CodePudding user response:
Package array. An array of objects;
import java.util.Arrays;
//shopping cart type
Public class ShoppingCar {
//define an array, save the products
The Product [] car;
Int b;
Int size=0;//save the amount of products in the shopping cart
Public ShoppingCar () {
//car=new Product [5].
}
//saved to a product in the array
Public void the add (Product a) {
The car=new Product [5].//why this on the construction method can, in this is a null pointer exception?
If (size>=car. Length) {
The car=Arrays. CopyOf (car, car. Length * 3);
}
The car [size]=a;
size++;
}
//deleted from the shopping cart product
Public void the delete (Product a) {
for (int i=0; I & lt; The size; I++) {
If (car [I] equals (a)) {
The car [I]=car [size - 1);
Size -; }
}
}
//traverse in the shopping cart products, if you have a product, a is removed from the array
//clearing
Public void cash () {
Double o=0;
for (int i=0; I & lt; The size; I++) {
System. Out. Println (" you buy goods for "+ car [I] name +" you buy commodity prices as "+ car [I] price);
O +=car [I]. Price;
}
System. Out. Println (" you buy goods total price is "+ o);
//walking down in the group product, the price price accumulative
//print the product in the shopping cart shopping list and total prices
}
}
CodePudding user response:
In the constructor, the object is created for the member variable car when I was allocated memory; And object is created in the add words won't give a member variable car allocated memory, only when calls the add method to allocate memory, so obviously, if haven't invoke the add after creating objects, the car has been null, if go to outside calls the add method, such as cash or delete method, then used car member variable words will protect null pointer errors (because the add not been called, the car has been a null).