gpt4 book ai didi

C# 给变量赋新值

转载 作者:行者123 更新时间:2023-11-30 20:21:14 25 4
gpt4 key购买 nike

所以我是 C# 的新手,实际上我大约半小时前才开始学习语法。

我到现在为止所做的只是搞乱了语法并制作了一个只有几行代码的交互式输入程序。当我输入完代码并想运行该程序时,它给了我一个错误。

        Console.Write("What is your name?: ");
string name = Console.ReadLine(); //'name' used here
Console.WriteLine("Hello " + name);
Console.ReadLine();

Console.Write("How old are you?: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("So you're name is " + name + " and you are " + age + " years old?");
Console.ReadLine();

Console.Write("Tell me, yes or no?: ");
string answer = Console.ReadLine();


if (answer == "no" || answer == "No")

{
Console.Write("Ahh okay, what was your name again?: ");
string name = Console.ReadLine(); //'name' used here
}

“不能在此范围内声明名为‘name’的局部变量或参数……”

我知道问题一定出在代码的最后一行,我在其中为字符串“name”分配了一个新值。我确信这在 PHP 中是可能的,为变量分配新值。正如我所说,我对 C# 完全陌生,我想知道是否有办法做到这一点?

最佳答案

只是你不能声明一个变量两次。当您键入 string name 时,您就是在声明它。尝试如下:

    string name;
Console.Write("What is your name?: ");
name = Console.ReadLine();
Console.WriteLine("Hello " + name);
Console.ReadLine();

Console.Write("How old are you?: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("So you're name is " + name + " and you are " + age + " years old?");
Console.ReadLine();

Console.Write("Tell me, yes or no?: ");
string answer = Console.ReadLine();


if (answer == "no" || answer == "No")

{
Console.Write("Ahh okay, what was your name again?: ");
name = Console.ReadLine();
}

希望这对您有所帮助。

关于C# 给变量赋新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34472395/

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