((JAVA)为我的自动售货机执行while循环

问题描述 投票:-1回答:1

此项目,我使用带有开关大小写的do while循环来检查输入的大小写是否匹配。我运行代码,但结果不是我想要的。我期望的是,如果用户键入错误的大小写,则do while循环将循环回到用户需要输入大小写的输入。

这里是代码

package vending.machine;
    import java.util.Scanner;
    import java.util.*;
    import java.util.ArrayList;
    import static vending.machine.adddrinks.drinksList;

public class VendingMachine {
    public static void main (String []args){
        Scanner sc= new Scanner(System.in);

        double money;
        double total;
        double balance;

        do{
            System.out.println("\nPlease insert money:");
            money = sc.nextDouble();
            if(money < 1.2){
                System.out.println("Not enough money");
            }
        }while(money < 1.2);
        System.out.println("What drinks are you looking for");
        adddrinks.showDrinks();
        adddrinks.viewDrinks();

        System.out.print("Select: 1 or 2 or 3 or 4\n");
        int select=sc.nextInt();

        do{
            switch(select){
                case 1:{
                    total = adddrinks.drinksList.get(0).getdrinkPrice();
                    balance = money - total;
                    System.out.println("Here is your balance: " + balance);
                    break;
                }
                case 2:{
                    total = adddrinks.drinksList.get(1).getdrinkPrice();
                    balance = money - total;
                    System.out.println("Here is your balance: " + balance);
                    break;
                }
                case 3:{
                    total = adddrinks.drinksList.get(2).getdrinkPrice();
                    balance = money - total;
                    System.out.println("Here is your balance: " + balance);
                    break;
                }
                case 4:{
                    total = adddrinks.drinksList.get(3).getdrinkPrice();
                    balance = money - total;
                    System.out.println("Here is your balance: " + balance);
                    break;
                }

                default:{
                    System.out.println("Invalid");
                    break;
                }
            }

        }while(select<5);
    }
}

这是结果enter image description here

java
1个回答
-1
投票

根据我对您的代码的理解。当输入为5时,表示输入无效。之后,它将转到while语句并检查那里的条件。如果您在开关箱内并选择任何随机箱,它将显示为无效。之后,取决于您输入的号码。 If the number is less than 5, It will again go to switch case. Note that not 5 but less than 5因为没有意义,因此应假设购买饮料所需的最低数量将此条件更改为while(balance<1.2)。这将在每次喝酒后检查病情,并希望能做您希望的事情。在侧面注意:使您的代码模块化。

© www.soinside.com 2019 - 2024. All rights reserved.