为什么如果我输入的数字超过 2,我没有得到循环?

  • 本文关键字:循环 如果 数字 java
  • 更新时间 :
  • 英文 :


所以,我的老师给我们做了一个活动。我们需要用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次。

最新更新