c# - 在 switch 语句中输入其他选项时值不变
问题描述
伙计们,我只是想要一些帮助。对不起,我是 C# 编程的新手。我的问题是,当我输入一个值时,比如说我输入 2,我想打印出来:(到目前为止插入:23 个中的 0 个。)但是发生的情况是它显示了相同的苏打水值,即 30 而不是 23 .
namespace VendingMachine
{
class Program
{
static void Main(string[] args)
{
int itemPrice = 0;
int moneyAvailable = 0;
int change = 0;
int soda = 30;
int juice = 23;
int water = 15;
string userChoice;
// Menu
Console.WriteLine();
Console.WriteLine("1. Soda = P30");
Console.WriteLine("2. Juice = P23");
Console.WriteLine("3. Water = P15");
Console.WriteLine("4. Exit");
Console.WriteLine();
// Values entered by the user
Console.Write("Your choice: ");
userChoice = Console.ReadLine();
Console.WriteLine("================================");
// THE MAIN PROBLEM
if (itemPrice < soda)
{
Console.WriteLine($"Inserted so far: P0 out of P{soda}");
}
Console.Write("Enter the amount of Money!: P");
moneyAvailable = int.Parse(Console.ReadLine());
switch (userChoice)
{
case "1":
itemPrice = itemPrice + soda;
break;
case "2":
itemPrice = itemPrice + juice;
break;
case "3":
itemPrice = itemPrice + water;
break;
default:
Console.WriteLine("Invalid. Choose 1, 2 or 3.");
break;
}
解决方案
您正在使用带有错误变量名的字符串插值
if (itemPrice < soda)
{
Console.WriteLine($"Inserted so far: P0 out of P{itemPrice}");
// ^^^^^^^^^^ Problem is here
}
而不是每次都打印苏打水的价值itemPrice
。
这个带有 if 条件的打印语句应该转到switch 语句的末尾
就像是,
Console.Write("Enter the amount of Money!: P");
moneyAvailable = int.Parse(Console.ReadLine());
switch (userChoice)
{
case "1":
itemPrice = itemPrice + soda;
break;
case "2":
itemPrice = itemPrice + juice;
break;
case "3":
itemPrice = itemPrice + water;
break;
default:
Console.WriteLine("Invalid. Choose 1, 2 or 3.");
break;
}
if (itemPrice < soda)
{
Console.WriteLine($"Inserted so far: P0 out of P{itemPrice}");
}
推荐阅读
- node.js - 如何防止“npm install”或“npm remove”删除我的个人包?
- python - DeprecationWarning:不推荐使用 AppURLopener 调用请求的样式
- python - Python GTK 3+:如何在 Combobox 小部件中居中文本?
- java - 程序未读取第一个字符串输入
- javascript - 构建自己的调用栈
- spring-el - SpEL 中 SimpleEvaluationContext.forReadOnlyDataBinding() 的令人困惑的行为
- javascript - 加载资源失败:服务器使用 Js、ajax、php 在联系表单上响应状态为 404(未找到)
- python - 如何在sklearn中构建大小大致平衡的集群
- java - 找不到错误
- sorting - Pascal - 不兼容的类型:得到“扩展数组”,预期“QWord”/错误