2013-12-13 15 views
0

我試圖讓這個程序添加到雙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."); 
     } 
    } 
} 

回答

1

list中有3個元素並要求第4個元素。

for(int i = 0; i<4; i++){ 

這應該是

for(int i = 0; i<currentTops.size(); i++){ 

由於您的列表中不具有4種元素的投擲例外。總是使用size()方法,這樣你就不用擔心循環索引。

編輯:

對於停止循環

} 
     else{ 
      System.out.println("Sorry, one or more of the entered toppings" 
       + " cannot be offered."); 
      break; 
     } 
+0

是的,我只是得到印刷現在2倍的其他消息。我怎樣才能把這個加起來? – user3098822

+0

@ user3098822在else中使用'break'語句。這將停止循環furthur –

+0

@ user3098822:嘗試使用'equalsIgnoreCase'而不是'equals'。 –

0

嘗試這樣

for(int i = 0; i<currentTops .size(); i++){ 
    topPrice+=currentTops .get(i); 
} 
0

你只需要在列表中3個元素。

因此最後一個元素的索引是2,但你試圖讓指數3.這就是例外告訴你

java.lang.IndexOutOfBoundsException:指數:3,大小:3

使用

for(int i = 0; i<currentTops.size(); i++){ 
0

變化for(int i = 0; i<4; i++)for(int i = 0; i<currentTops.size(); i++)。應該這樣做。不要在這些類型的場景中硬編碼列表的大小。這裏的問題是,你的列表只有3的大小,這意味着你只能遍歷到2.這就是你在這裏失蹤。

0

java.lang.IndexOutOfBoundsException的原因是currentTops list只包含三個元素,但您正在訪問第四個元素。

變化

for(int i = 0; i<4; i++) 

for(int i = 0; i<currentTops.size(); i++) 
1

變化

for(int i = 0; i<4; i++){ 

for(int i = 0; i<currentTops.size(); i++){ 

或美國E對於每個迴路

for(String s:currentTops){ 

在這裏,而不是currentTops.get(i)使用,但是是擺脫我的錯誤的s