我正在制作一个自动售货机程序,我不知道如何在我的 for 循环中使用用户选择,因为当我将选择放在循环中时它会给我一个错误。
public class PopGenerator {
double price[] = {2.49, 1.25, 3.49, 3.25, 2,25, 1.30, 3.40, 3.49, 2.50, 3.00};
public void beveragechoice()
{
Scanner c = new Scanner(System.in);
int choice = c.nextInt();
double price[] = {2.49, 1.25, 3.49, 3.25, 2.25, 1.30, 3.40, 3.49, 2.50, 3.00};
switch(choice)
{
case 1:
System.out.println("This beverage costs $" + price[0]);
break;
case 2:
System.out.println("This beverage costs $" + price[1]);
break;
case 3:
System.out.println("This beverage costs $" + price[2]);
break;
case 4:
System.out.println("This beverage costs $" + price[3]);
break;
case 5:
System.out.println("This beverage costs $" + price[4]);
break;
case 6:
System.out.println("This beverage costs $" + price[5]);
break;
case 7:
System.out.println("This beverage costs $" + price[6]);
break;
case 8:
System.out.println("This beverage costs $" + price[7]);
break;
case 9:
System.out.println("This beverage costs $" + price[8]);
break;
case 10:
System.out.println("This beverage costs $" + price[9]);
}
}
public void change()
{
System.out.println("Enter money put into the machine: ");
Scanner m = new Scanner(System.in);
int money = m.nextInt();
for(int x = choice; x >= 0 ; x--)
if (money == price[x])
{
System.out.println("No change.");
}
else
{
System.out.print("Your change is: ");
System.out.print(money - price[x]);
}
}
}
您可以简化这两种方法,以避免有多个扫描程序或通过它们传递变量,如下所示:
public void beveragechoice() {
double prices[] = {2.49, 1.25, 3.49, 3.25, 2,25, 1.30, 3.40, 3.49, 2.50, 3.00};
System.out.println("Select one beverage");
Scanner c = new Scanner(System.in);
int choice = c.nextInt();
if (choice > 0 && choice <= prices.length) {
double p = prices[choice - 1];
System.out.println("This beverage costs $" + p);
System.out.println("Enter money put into the machine: ");
double money = c.nextDouble();
if (money == p) {
System.out.println("No change.");
} else {
System.out.println("Your change is: $" + (money - p));
}
}
}