允许最终用户第二次机会?

时间:2014-09-09 20:53:17

标签: c#

我正在用C#编写一个文本游戏。

if (DoorHallwayMB1 == "door")
{
   Console.WriteLine("You open the rusty door to reveal a janitor's closet, you quickly stock up \non ammo, and return to the Hangar.");
}

if (DoorHallwayMB1 == "corridor")
{
   Console.WriteLine("You walk down the corridor and find some ammo forr your pistol. You return to the hangar");
}
else
{
   Console.WriteLine("invalid. Make sure you type either 'corridor' or 'door'");
}

请注意,如果到达else语句,程序将终止。我怎样才能使它回到if语句的开头?

4 个答案:

答案 0 :(得分:2)

另一种选择,您也可以使用switch

bool isValid = false;
string DoorHallwayMB1 = string.Empty;
while (!isValid)
{
    Console.WriteLine("What will it be?");
    DoorHallwayMB1 = Console.ReadLine();
    switch (DoorHallwayMB1)
    {
        case "door":
            Console.WriteLine("You open the rusty door to reveal a janitor's closet, you quickly stock up \non ammo, and return to the Hangar.");
            isValid = true;
            break;
        case "corridor":
            Console.WriteLine("You walk down the corridor and find some ammo forr your pistol. You return to the hangar");
            isValid = true;
            break;
        default:
            Console.WriteLine("invalid. make sure you type either 'corridor' or 'door'");
            break;
    }
}

答案 1 :(得分:1)

你想要一个循环:

bool valid = false;
while(!valid)
{
    //get input
    if(/*valid input*/)
    { 
        //do whatever
        valid = true;
    }
}

答案 2 :(得分:0)

你需要一个循环:

while( true )
{
    //DoorHallwayMB1 = ....
    if (DoorHallwayMB1 == "door")
    {
       Console.WriteLine("You open the rusty door to reveal a janitor's closet, you quickly stock up \non ammo, and return to the Hangar.");
       break; //exit loop
    }
    if (DoorHallwayMB1 == "corridor")
    {
       Console.WriteLine("You walk down the corridor and find some ammo forr your pistol. You return to the hangar");
       break; // exit loop
    }
    else
    {
       Console.WriteLine("invalid. make sure you type either 'corridor' or 'door'");
    }
}

答案 3 :(得分:0)

您需要使用合适的退出机制将代码包装在循环中。例如

bool exitCondition=false;
while (true)
{
    // your code which also sets exitConditon
    if(exitCondition) {break;}
}
相关问题