所以,我的老师给我们做了一个活动。我们需要用Stacks制作一个关于果篮的程序。所以问题是,如果我对我的问题输入超过2〃;你想抓多少水果&";,第一次尝试后,我无法输入任何内容。
public class FruitBasket {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Stack <String> fruits = new Stack <String>();
System.out.println("Catch and Eat any of these Fruits: ('Apple' , 'Orange' , 'Mango' , ' Guava ' ) ");
System.out.print("How many fruit would you like to catch?");
int size = scan.nextInt();
System.out.println("Choose a fruit to catch. Press A , O , M or G.");
scan.nextLine();
int x = 1;
do {
String input = scan.nextLine();
System.out.println("Fruit " + x + " of " + size+ ": " + input);
x++;
switch(input) {
case "a":
fruits.add("Apple");
break;
case "o":
fruits.add("Orange");
break;
case "m":
fruits.add("Mango");
break;
case "g":
fruits.add("Guava");
break;
}
}while(x == size);
System.out.println("Your basket now has: " + fruits);
System.out.println(); //Spacing
}
}
这里的问题是do-while
循环中的条件。您当前的条件是,只有在x == size
。
从x = 1
开始,在do-while
循环的do
块中递增x
。这意味着,重复循环的唯一方法是将size
输入为2
。因为在检查时,您指定的while(x == size)
条件是true
。
在所有其他情况下,条件为false
,并且循环不会重复。
您可能希望将循环条件更改为
while(x <= size)
循环size - 1
的次数,使do
块总共运行size
次。