java - 如何在更改方法中使用用户选择
问题描述
我正在制作一个自动售货机程序,但我不知道如何在我的 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));
}
}
}
推荐阅读
- python-3.x - 使用 requirements.txt 和 Heroku 时找不到匹配的 pickle 分布
- ruby-on-rails - has_one :through 协会!如何在 AccountHistory 和 Supplier 之间建立连接
- vue.js - Vue:V-select下拉菜单不断触发键盘在iOS浏览器上弹出
- android - Xamarin 应用程序在三星 Galaxy S8 上崩溃 - 未识别出任何模式
- haskell - 代数数据类型(预期)名称冲突..怎么办?
- django - 我在 Django 中使用“success_url”时遇到问题
- java - 创建新活动后如何显示RecyclerView,Android Firebase
- c# - EFCore Linq:仅选择具有最大值的记录
- c# - DataBinding IList 时如何显示选项卡
在 DataGridView - powershell - 使用powershell执行命令以输出窗口