所以我对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'。我确信这在PHP中是可行的,为变量赋值。正如我所说,我对C#全新,我想知道是否有办法做到这一点?
答案 0 :(得分:2)
那是因为你重新声明了两次变量名。只需删除字符串声明。您也无法在子范围中定义相同的变量名称。 ({ }
之间)
if (answer == "no" || answer == "No")
{
Console.Write("Ahh okay, what was your name again?: ");
name = Console.ReadLine();
}
答案 1 :(得分:2)
只是你不能两次声明一个变量。当您键入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();
}
希望这有帮助。
答案 2 :(得分:2)
问题是您在此行声明了字符串变量name
:
string **name** = Console.ReadLine();
然后,在if
语句中,您尝试再次声明它。如果你的意思是“重用”同一个变量,只需删除字符串部分(告诉c#你声明一个字符串类型的变量):
name = Console.ReadLine();
玩得开心!
答案 3 :(得分:0)
名称已经宣布。要分配新值,您无需指定变量类型。因此,请在最后一行string
之前删除name
。
答案 4 :(得分:0)
尝试删除“字符串”?
{
Console.Write("Ahh okay, what was your name again?: ");
**name** = Console.ReadLine();
}