我正在做一个简单的项目,只是为了让自己保持新鲜感。决定做一个自动贩卖机。好吧,我到最后进行测试。它确实适合情况1和2,但是当我选择情况3时,它要么完成整个程序,要么当我选择零食选项时将其更改为if / else,如果选择情况3,它将停止运行。小吃。为什么这样做呢?我该怎么解决?
import java.util.Scanner;
public class Vending
{
public static void main(String[] args)
{
int choice;
double deposit = 0;
double total = 0;
Scanner keyboard = new Scanner(System.in);
boolean test = true;
do
{
System.out.println("\nVending Machine Menu");
System.out.println("\n \n1. View Items");
System.out.println("2. Put Money into Machine");
System.out.println("3. Select an Item");
System.out.println("4.Recieve Change");
System.out.println("5.Exit");
System.out.println("\nPlease Make a Selection: ");
choice = keyboard.nextInt();
switch(choice)
{
case 1 :
System.out.println("\n 1. Fizzy soda : $0.50 \n 2. Gummi Possums : $0.25"
+ "\n 3. Doggy Bones : $0.25 \n 4. Fruity Punch : $0.50");
System.out.println("Press ENTER to continue");
try{System.in.read();}
catch(Exception e){}
break;
case 2:
System.out.println("Enter amount to deposit: ");
deposit = keyboard.nextDouble();
total = total + deposit;
break;
case 3:
Scanner keypad = new Scanner(System.in);
System.out.println("\n 1. Fizzy soda : $0.50 \n 2. Gummi Possums : $0.25"
+ "\n 3. Doggy Bones : $0.25 \n 4. Fruity Punch : $0.50");
System.out.println("\nSelect an item: ");
int snack = keypad.nextInt();
if (total > 0)
{
if(snack == 1)
{
if (total >= .5)
{
System.out.println("The Vending Machine dispenses a FIZZY SODA");
total = total - .5;
}
else
{
System.out.println("Deposit more money");
}
}
else if(snack == 2)
{
if (total >= .25)
{
System.out.println("The Vending Machine dispenses a package of GUMMI POSSUMS");
total = total - .25;
}
else
{
System.out.println("Deposit more money");
}
}
else if(snack == 3)
{
if(total >= .25)
{
System.out.println("The Vending Machine Dispenses a package of DOGGY BONES");
total = total - .25;
}
else
{
System.out.println("Deposit more money");
}
}
else if(snack == 4)
{
if(total >= .5)
{
System.out.println("The Vending Machine Dispenses a can of FRUITY PUNCH");
total = total - .5;
}
else
{
System.out.println("Deposit more money");
}
}
}
else
{
System.out.println("Please deposit some money");
}
keypad.close();
case 4:
System.out.println("You recieve " + total + " in change from the Vending Machine");
total = 0;
case 5:
System.exit(0);
}
}
while (test == true);
keyboard.close();
}
}
最佳答案
如果您不想执行下一个break
语句,则需要在case
语句的末尾使用case
:
case 3:
// do something
break; // break to avoid executing case 4
case 4:
// ...