(我是一个初学者,刚开始在大学/ A级学习C#,所以我的代码效率很低)。
无论如何,下面的代码只是我的“ CinemaBookingSystem”的一部分,并且由于我的变量filmName是在切换用例之外声明的,因此它表示在此上下文中不存在“ filmName”。我尝试使用“公共静态字符串filmname =“ example”;“方法,但该方法不起作用,因为我在不同的if语句中多次声明了电影名称。
if (filmNum == 1)
string filmName = "Teenage Horror Film";
if (filmNum == 2)
;
string filmName = "How I Live Now";
switch (filmNum)
{
case 1:
case 2:
if (Age >= 15)
{
Console.WriteLine("What date do you want to watch the film? (Format : dd/mm/yyyy) :");
DateTime dateChoice = DateTime.Parse(Console.ReadLine());
DateTime now = DateTime.Now;
DateTime limit = now.AddDays(7);
if (dateChoice >= now && dateChoice <= limit)
{
Console.WriteLine("--------------------");
Console.WriteLine("Aquinas Multiplex");
Console.WriteLine("Film : {0}", filmName);
Console.WriteLine("Date : {0}", dateChoice);
Console.WriteLine("--------------------");
}
else
{
Console.WriteLine("Access denied - date is invalid");
}
}
while (Age < 15)
{
Console.WriteLine("Access denied - You are too young");
}
break;
}
答案 0 :(得分:1)
肯尼,因为您在条件语句中声明了变量filmName
,所以在switch
中无法访问它。您需要在if
之前声明它:
string filmName = string.empty;
if (filmNum == 1) ;
{
filmName = "Teenage Horror Film";
}
if (filmNum == 2) ;
{
filmName = "How I Live Now";
}
switch (filmNum)
{
case 1: case 2:
if (Age >= 15)
{
Console.WriteLine("What date do you want to watch the film? (Format : dd/mm/yyyy) :");
DateTime dateChoice = DateTime.Parse(Console.ReadLine());
DateTime now = DateTime.Now;
DateTime limit = now.AddDays(7);
if (dateChoice >= now && dateChoice <= limit)
{
Console.WriteLine("--------------------");
Console.WriteLine("Aquinas Multiplex");
Console.WriteLine("Film : {0}", filmName);
Console.WriteLine("Date : {0}", dateChoice);
Console.WriteLine("--------------------");
}
else
{
Console.WriteLine("Access denied - date is invalid");
}
}
while (Age < 15)
{
Console.WriteLine("Access denied - You are too young");
}
break;
}
}
}
答案 1 :(得分:1)
您需要在if语句之外声明它,并在其中声明一个值(确保有一个默认值,以防万一没有被触发)。 另外,如果if语句后面有分号。