我正在尝试扫描一个单词,然后按下输入后,将使用for循环将其放置在ArrayList的第n个位置。我在哪里放置(i)以使其有效?我不能把它放进去像topScan.next(i);?
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 :(得分:0)
我假设你试图遍历for-loop,直到用户输入了添加的浇头数量。这是一些代码来执行此操作。此外,每次使用时都不需要创建新的扫描仪,所以我改变了它。
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();
}