2013-12-13 85 views
-1

我試圖掃描一個單詞後按下輸入它將被放置在ArrayList中的第n個位置使用for循環。 (i)在這段代碼中的作用是什麼?我不能把它放在像我可以topScan.next(i);?掃描到一個ArrayList Java

for (int i = 0; i>topsNo; i++); { 
    System.out.println("Enter next topping :"); 
    Scanner topScan = new Scanner(System.in); 
    b.currentTops = topScan.next(); 
} 

編輯:

我把它不清楚,因此我要添加類的其餘部分:

public static void main(String [] Args) { 
PizzaBase a = new PizzaBase(); 
Pizza p = new Pizza(); 
PizzaToppings b = new PizzaToppings(); 


//SCAN FOR KEYWORD INGRIDIENTS TO SEE WHAT IS OK 


Scanner s = new Scanner(System.in); 
String base; 
System.out.println("Enter base: "); 

base = s.next(); 
a.setBase(base); 

int topsNo = 0; 

System.out.println("Enter number of desired toppings: "); 
Scanner nt = new Scanner(System.in); 

if(nt.hasNextInt()){ 
     topsNo = nt.nextInt(); 
    }else{ 
     System.out.println("Try again (re-enter number of toppings 1-9)"); 
    } 

編輯:按照要求,PizzaToppings類:

public class PizzaToppings { 


List<String> tops = new ArrayList<String>(); 
List<Double> prices = new ArrayList<Double>(); 
List<String> currentTops = new ArrayList<String>(); 
double topPrice; 
public void pizzaTop() { 

    currentTops.add("mushrooms"); 
    currentTops.add("cheese"); 
    currentTops.add("ham"); 
    currentTops.add("chicken"); 

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

    if(currentTops.get(i).equalsIgnoreCase("cheese")){ 
      topPrice+=(1.0); 
     } else if(currentTops.get(i).equalsIgnoreCase("sweetcorn")){ 
      topPrice+=(2.0); 
     } else if(currentTops.get(i).equalsIgnoreCase("mushrooms")){ 
      topPrice+=(1.2); 
     } else if(currentTops.get(i).equalsIgnoreCase("chicken")){ 
      topPrice+=(1.25); 
     } 
     else{ 
      System.out.println("Sorry but topping "+ currentTops.get(i) 
       + " cannot be offered."); 
      break; 
     } 
    } 


} 
+0

什麼是'topsNo'?什麼是'b'? –

+2

您不必在每次迭代時都創建一個新的掃描器... – TheLostMind

+0

您從哪裏收到要放入其中的索引?這裏沒有說。 – Jops

回答

0

我假設你正試圖遍歷,直到用戶輸入了澆頭的數量已被添加。這是一些代碼來做到這一點。另外,每次使用時都不需要創建新的掃描儀,所以我改變了它。

Scanner theKeyboard = new Scanner(System.in); 
    String base; 
    System.out.println("Enter base: "); 

    base = theKeyboard.next(); 
    a.setBase(base); 



    System.out.println("Enter number of desired toppings: "); 
    int topsNo = theKeyboard.nextInt(); 

    //Alternately use a while loop here incrementing 'i' each time a topping is entered 
    for (int i = 0; i < topsNo; i++) 
    { 
     System.out.println("Enter next topping :"); 
     b.currentTops = theKeyboard.next(); 
    }