簡體   English   中英

為什么如果我輸入一個大於 2 的數字我沒有得到循環?

[英]Why if I input a number more than 2 I don't get the loop?

所以,我的老師給了我們一個活動。 我們需要使用 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 這意味着,重復循環的唯一方法是輸入size2 因為那樣,您指定的while(x == size)條件在檢查時為true

在所有其他情況下,條件為false並且您的循環不會重復。

您可能希望將循環條件更改為

while(x <= size)

to loop size - 1次,它運行do塊的總size次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM