gpt4 book ai didi

C# - 更换背包中的元素

转载 作者:太空狗 更新时间:2023-10-30 01:30:56 26 4
gpt4 key购买 nike

我正在尝试创建一个简单的背包程序。这是学校的作业,我快完成了,只是我无法用新的东西替换我背包里的东西。

我猜测为什么它可能不起作用是因为我无法替换 item 因为它在全局范围内,但我不知道如何修复它。这是代码:

static void Main(string[] args)
{
bool isRunning = true;
while (isRunning)
{
Console.WriteLine("\n\tWelcome to the backpack!");
Console.WriteLine("\t[1]Add an item");
Console.WriteLine("\t[2]Show contents");
Console.WriteLine("\t[3]Clear contents");
Console.WriteLine("\t[4]Exit");
Console.Write("\tChoose: ");

int menyVal = Convert.ToInt32(Console.ReadLine());

string item;
item = "Empty space";


switch (menyVal)
{
case 1:
Console.WriteLine("\n\tContents of backpack:");
Console.WriteLine("\n\t" + item);
Console.WriteLine("\n\tWhat do you want to replace " + item + " with?");
item = item.Replace(item, Console.ReadLine());
Console.WriteLine("\n\tYou have packed " + item + " in your backpack");
break;
case 2:
Console.WriteLine("\n\tContents of backpack:");
Console.WriteLine("\n\t" + item);
Console.WriteLine("\n\tPress any key...");
Console.ReadKey();
break;
case 3:
item = "Tom plats";
Console.WriteLine("\n\tYou have emptied the backpack!");
break;
case 4:
isRunning = false;
break;
default:
Console.WriteLine("Incorrect input!");
break;
}
}
}

关于如何解决这个问题的任何想法?非常感谢提示!谢谢!

最佳答案

移动赋值

string item;
item = "Empty space";

在 while 循环之前。

现在,每次循环都会覆盖项目值。

下面是整个代码在更改后的样子:

static void Main(string[] args)
{
bool isRunning = true;
string item = "Empty space";

while (isRunning)
{
Console.WriteLine("\n\tWelcome to the backpack!");
Console.WriteLine("\t[1]Add an item");
Console.WriteLine("\t[2]Show contents");
Console.WriteLine("\t[3]Clear contents");
Console.WriteLine("\t[4]Exit");
Console.Write("\tChoose: ");

int menyVal = Convert.ToInt32(Console.ReadLine());

switch (menyVal)
{
case 1:
Console.WriteLine("\n\tContents of backpack:");
Console.WriteLine("\n\t" + item);
Console.WriteLine("\n\tWhat do you want to replace " + item + " with?");
item = Console.ReadLine());
Console.WriteLine("\n\tYou have packed " + item + " in your backpack");
break;
case 2:
Console.WriteLine("\n\tContents of backpack:");
Console.WriteLine("\n\t" + item);
Console.WriteLine("\n\tPress any key...");
Console.ReadKey();
break;
case 3:
item = "Tom plats";
Console.WriteLine("\n\tYou have emptied the backpack!");
break;
case 4:
isRunning = false;
break;
default:
Console.WriteLine("Incorrect input!");
break;
}
}
}

关于C# - 更换背包中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42165289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com