在java中的while循环之后,程序不会打印任何内容

时间:2018-02-19 09:32:25

标签: java arrays while-loop

我的程序代表一个基本的自动售货机,但即使我输入-1并且没有显示任何错误,程序也不会打印任何内容。 该程序似乎不会在循环之前退出整个程序! 我的节目是

double userMoney = 0.0;
String userSelection = "";
String userLetter;

System.out.println("Please enter how much money you want to spend( enter -1 to shut down)");
System.out.println("");
userSelection = scan.next();

userMoney = scan.nextDouble();
userLetter = scan.next();

boolean exit = false;

while (!exit) {

    if (userSelection.equals("-1")) {
        System.out.println("Thank you for your business");
        exit = true;
    }
    else if (userMoney >= 1) {
        System.out.println("A-Milk, B-Soda, C-Candy Bar, D-Gummy Bear, EChips, X-exit");
    }
    else {
        System.out.println("Invalid Entry");
    }
}
switch(userLetter.toUpperCase()){

            case "A":
                if(userMoney >= 2.00){
                    userMoney -= vendingPrices[0];
                    vendingQuantity[0]--;
                    System.out.println("You have bought " + vendingItems[0] + " for $2.00. You still have $" + userMoney + " left.");
                    System.out.println("");
                }
                else{
                    System.out.println("Sorry!, you do not have enough money to buy this item.");
                }
            break;          

2 个答案:

答案 0 :(得分:2)

好吧,首先,你的循环条件不对。也许你想要更像的东西:

boolean exit = false;
while(!exit) {
    ...
}

而且你还需要在程序循环中查询用户,以便你可以捕获用户退出,所以......

while(!exit) {
   userSelection = scan.next();
   if (userSelection.equals("-1")) {
      System.out.println("Thank you for your business");
      exit = true;
   }
}

用一个有效的解决方案回答你的问题,因为你有一些反模式和奇怪的方法,我已经创建了一个自动售货机的版本,但它完全以面向对象的方式重写: http://www.browxy.com/SubmittedCode/14314

也许它会起到灵感作用?

答案 1 :(得分:2)

你应该按照以下方式做一些事情:

double userMoney = 0.0;
String userSelection = "";
String userLetter;

System.out.println("Please enter how much money you want to spend( enter -1 to shut down)");
System.out.println("");
userSelection = scan.next();

userMoney = scan.nextDouble();
userLetter = scan.next();

boolean exit = false;
System.out.println("Tesying2");
while (!exit) {
    System.out.println("Testing");
    if (userSelection.equals("-1")) {
        System.out.println("Thank you for your business");
        exit = true;
    }
    else if (userMoney >= 1) {
        System.out.println("A-Milk, B-Soda, C-Candy Bar, D-Gummy Bear, EChips, X-exit");
    }
    else {
        System.out.println("Invalid Entry");
    }
}