当我输入水、茶、苏打水等饮料时,循环出现问题。
另外,我不希望它在用户输入饮料选择之前打印退货,但每次都会出现这种情况。
import java.util.Scanner;
public class Vending
{
public static void main(String[] args)
{
System.out.print("Enter a command = ");
double balance = 0.0;
String a;
// scanner input
Scanner in = new Scanner(System.in);
while (in.hasNext())
{
String command = in.nextLine();
if (command.equals("penny"))
{
balance = balance + 0.01;
System.out.println("balance = " + balance);
}
if (command.equals("nickel"))
{
balance = balance + 0.05;
System.out.println("balance = " + balance);
}
if (command.equals("dime"))
{
balance = balance + 0.10;
System.out.println("balance = " + balance);
}
if (command.equals("quarter"))
{
balance = balance + 0.25;
System.out.println("balance = " + balance);
}
if (command.equals("dollar"))
{
balance = balance + 1.00;
System.out.println("balance = " + balance);
}
else if (command.equals("break"))
{
break;
}
else if (command.equals("water"))
{
System.out.println("Water");
System.out.println("balance = " + balance - 1.25);
}
else if (command.equals("tea"))
{
System.out.println("Tea");
System.out.println("balance = " + balance - 1.50);
}
else if (command.equals("soda"))
{
System.out.println("soda");
System.out.println("balance = " + balance - 1.75);
}
else
{
System.out.println("return " + balance + " to customer");
}
balance++;
}
}
}