so I've been scratching over why my code doesn't work. I have 2 classes, the first one is where I have my getters and setters:
public class ShopItems {
private String itemName;
private double price;
public double getPrice(){
return price;
}
public String getItemName(){
return itemName;
}
private void setPrice(p){
price = Math.abs(p);
}
public ShopItems(String i, double p){
itemName = i.toUpperCase();
setPrice(p);
}
}
and here is my second class, where I make an ArrayList:
public class ShopLedger {
private ArrayList<ShopItems> shoppingList;
//I want to make a deep copy of the items in the parameter into shopping list.
public ShopLedger(ArrayList<ShopItems> s){
shoppingList = new ArrayList<ShopItems> (s);
for(int i=0;i<s.size();i++){
shoppingList.set(i,s.get(i));
}
}
//And here is where things go wrong. I want the method to return the price of the item
//in the parameter, and return null if the item name cannot be found.
public Double getPrice(String itemName) {
for(int i=0;i<shoppingList.size();i++){
if(shoppingList.get(i).getItemName() == itemName){
return shoppingList.get(i).getPrice();
}
}
return null;
}
}
This is what I have now, and the code keeps giving me the error "java.lang.NullPointerException". My client class sets the shoppingList as:
Candy(2.3), Book(20.0), Pens(5.5), Tape(10.2)
and itemName is Pens
.
However, I've gone into debug mode and for some reason, this part of the getPrice method:
if(shoppingList.get(i).getItemName() == itemName){
return shoppingList.get(i).getPrice();
}
never executes. Please help!
You compare String with ==
Use equals(). "aaaa".equals("aaaa");