我試圖讓這個程序添加到雙topPrice根據我的列表的內容但是我得到的錯誤:如果基於一個列表,它不工作的聲明 - Java的
"Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at pizzaProject.PizzaToppings.pizzaTop(PizzaToppings.java:34)
at pizzaProject.PizzaBuild.main(PizzaBuild.java:30)"
所以我的問題是,我怎樣才能做到這一點沒有得到錯誤?另外,有沒有辦法來使用一張地圖並加上來自它的值,而不是做這個簡單的解決方案?
List<String> currentTops = new ArrayList<String>();
double topPrice;
public void pizzaTop() {
for(int i = 0; i<4; i++){
if(currentTops.get(i).equals("cheese")){
topPrice+=(1.0);
} else if(currentTops.get(i).equals("sweetcorn")){
topPrice+=(2.0);
} else if(currentTops.get(i).equals("mushrooms")){
topPrice+=(1.2);
} else if(currentTops.get(i).equals("chicken")){
topPrice+=(1.25);
}
else{
System.out.println("Sorry, one or more of the entered toppings"
+ " cannot be offered.");
}
}
}
是的,我只是得到印刷現在2倍的其他消息。我怎樣才能把這個加起來? – user3098822
@ user3098822在else中使用'break'語句。這將停止循環furthur –
@ user3098822:嘗試使用'equalsIgnoreCase'而不是'equals'。 –