2013-12-13 53 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(); 
    }