簡體   English   中英

如何使程序 go 回到特定的代碼行 C#

[英]How to make the program go back to specific line of code C#

我正在創建一個基於文本的選擇你自己的冒險游戲,如果在程序中選擇了其他死胡同選項,我希望能夠讓程序跳回到特定的代碼行。 我是 C# 的新手,還在學習,如果這是一個簡單的解決方案,請原諒我。 我目前正在使用返回; 只是停止程序。 這是我的代碼示例...

        Console.Write("Type OPEN or KNOCK: ");
        string doorChoice = Console.ReadLine();
        string capDoor = doorChoice.ToUpper();
        Console.WriteLine();

        if (capDoor == "OPEN")
        {
            Console.WriteLine(" The door is locked! See if one of your three keys will open it.");
            Console.Write("Enter a number (1-3): ");

            string keyChoice = Console.ReadLine();

            //Respone to the preferred key choice
            switch (keyChoice)
            {
                case "1":
                    Console.WriteLine(" You fumble getting the key into the lock, but it works!\n You open the door to find the room as if it were untouched. Strange.\n  TRY AGAIN.");
                    return;
                    

                case "2":
                    Console.WriteLine(" You choose the second key. The door doesn't open.\n TRY AGAIN");
                    return;

                case "3":
                    Console.WriteLine(" You choose the second key. The door doesn't open.\n TRY AGAIN");
                    return;
            }
        }
        else if (capDoor == "KNOCK")
        {
            Console.WriteLine(" A voice behind the door speaks to you. It says, \"Answer this riddle: \"");
            Console.WriteLine(" \"Poor people have it. Rich people need it. If you eat it you die. What is it?\"");
            
        }

我希望最終讓程序跳轉到 Console.Write("Enter a number (1-3): "); 這樣用戶就可以進行另一個選擇而不是重新啟動。 我確信有一個簡單的解決方案,我只是想不通。 提前致謝!

您需要將查詢放在一個循環中,只有在做出正確選擇時才離開。 因為你使用了一個 switch,它在每個 case 之后都使用關鍵字break ,而我提倡一個循環,它使用break離開,我們需要稍微不同的結構,因為我們不能通過發出來退出循環開關盒內的break

while(true){ //loop forever unless we break
        Console.Write("Enter a number (1-3): ");
        string keyChoice = Console.ReadLine();

        //Respone to the preferred key choice
        switch (keyChoice)
        {
            case "1":
                Console.WriteLine(" You fumble ...");
                break; //break out of the switch but not the loop
                
            case "2":
                Console.WriteLine(" You choose ...");
                continue; //restart the loop

            case "3":
                Console.WriteLine(" You choose ...");
                continue; //restart the loop

            default:
                Console.WriteLine(" That isn't a valid key number, enter 1, 2 or 3");
                continue; //restart the loop
        }
        break; //break out of the loop 
}

我已將您的開關修改為默認情況; 在您的代碼無法處理用戶輸入垃圾之前


當我們想要停止循環時,我們還可以使用我們設置的變量來控制循環:

    bool keepLooping = true;
    while(keepLooping){ 
        Console.Write("Enter a number (1-3): ");
        string keyChoice = Console.ReadLine();

        switch (keyChoice)
        {
            case "1":
                Console.WriteLine(" You fumble ...");
                keepLooping = false; //stop the loop from running next time 
                break;
                
            case "2":
                Console.WriteLine(" You choose ...");
                break; 

            case "3":
                Console.WriteLine(" You choose ...");
                break;

            default:
                ...
        } 
}

或者你可以放棄 switch/case 並使用ifbreak來退出循環:

while(true){ 
        Console.Write("Enter a number (1-3): ");
        string keyChoice = Console.ReadLine();

        if(keyChoice == "1"){
                Console.WriteLine(" You fumble ...");
                break; //exit the loop
        } else
                Console.WriteLine(" You choose ...");
}

如果用戶輸入了錯誤的密鑰或垃圾,這只會發出“錯誤的密鑰”消息。


盡量不要將您的代碼視為“如果轉到點 X”,而更像是“在不滿足某些條件時重復這部分代碼”——這是一個微妙的區別,但會鼓勵你考慮你需要的循環使


ps; 如果您使用一種提出問題並返回響應的方法,您的生活會變得更加簡單:

public static string Ask(string question){
    Console.WriteLine(question + " ");
    return Console.ReadLine();
}

像這樣使用它:

string keyChoice = Ask("Enter a key 1-3:");

我們可以改進一些東西來防止用戶進入垃圾:

public static int AskNumber(string question, int lower, int upper){
    Console.WriteLine(question + " ");

    int result; //variable for the result
    bool isNumber = int.TryParse(Console.ReadLine(), out result); //try turning the string into a number 

    //while not a number was entered or number was out of range 
    while(!isNumber || result < lower || result > upper) {
      //repeat the question
      Console.WriteLine(question + " ");

      //try parse their input again
      isNumber = int.TryParse(Console.ReadLine(), out result);
    }
    return result;
}

這是“循環直到滿足所需條件”的另一個代碼示例 - 所需條件是用戶輸入有效輸入

像這樣使用它:

int keyChoice = AskNumber("Which key? Enter 1, 2 or 3", 1, 3);

您可以確定響應將是 1、2 或 3,因此您不必在每個開關等中處理垃圾

雖然使用while(){}循環的建議確實是正確的,並且在高級語言中非常可取,但仍然有可能通過使用標簽和goto命令在 c# 中完全滿足您的要求:

<some code>
My_label:
<some other code>
goto My_label;

注意,這是一個相當低級的結構,因此完全由您來確保不會出現任何問題(例如,這可能會在沒有通知的情況下創建無限循環......)。 盡管如此,它仍然是一個有用的結構,例如可以用來跳出嵌套的代碼塊。

檢查微軟文檔: .NET 文檔

您可以使用 do-while 循環我不確定您的退出條件是什么

       int x;
            do
            {
                bool result = int.TryParse(Console.ReadLine(), out x);
                switch (x)    
                {
              
                case 1:
                    {
                       // some code  
                        break;
                    }
                case 2:
                    {
                        some code
                        break;
                    }
                default:
                    {
                        if (x == 3)
                        {
                            Console.WriteLine("Exit");
                        }
                        else
                        {
                            Console.WriteLine("Choose a number from 1 or 2");
                        }
                        break;
                    }
               }
        } while (x!=3);

您可以使用 goto 語句https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto

using System;
                    
public class Program
{
    public static void Main()
    {
        Console.Write("Type OPEN or KNOCK: ");
        string doorChoice = Console.ReadLine();
        string capDoor = doorChoice.ToUpper();
        Console.WriteLine();

        if (capDoor == "OPEN")
        {
            One:
            Console.WriteLine(" The door is locked! See if one of your three keys will open it.");
            Console.Write("Enter a number (1-3): ");

            string keyChoice = Console.ReadLine();

            //Respone to the preferred key choice
            switch (keyChoice)
            {
                case "1":
                    Console.WriteLine(" You fumble getting the key into the lock, but it works!\n You open the door to find the room as if it were untouched. Strange.\n  TRY AGAIN.");
                    goto One;
                    return;
                    

                case "2":
                    Console.WriteLine(" You choose the second key. The door doesn't open.\n TRY AGAIN");
                    return;

                case "3":
                    Console.WriteLine(" You choose the second key. The door doesn't open.\n TRY AGAIN");
                    return;
            }
        }
        else if (capDoor == "KNOCK")
        {
            Console.WriteLine(" A voice behind the door speaks to you. It says, \"Answer this riddle: \"");
            Console.WriteLine(" \"Poor people have it. Rich people need it. If you eat it you die. What is it?\"");
            
        }
    }
}

將 console.write 放入它自己的方法中,並在需要時調用該方法,例如從 if 語句或 case 語句中調用。 您不會將代碼 go 設置為特定的行號。 這不是像 BASIC 那樣的線性編程。

例如,我創建了一個名為 EnterNumber() 的方法:

 Console.Write("Type OPEN or KNOCK: ");
        string doorChoice = Console.ReadLine();
        string capDoor = doorChoice.ToUpper();
        Console.WriteLine();

        if (capDoor == "OPEN")
        {
            Console.WriteLine(" The door is locked! See if one of your three keys will open it.");
            EnterNumber();

            string keyChoice = Console.ReadLine();

            //Respone to the preferred key choice
            switch (keyChoice)
            {
                case "1":
                    Console.WriteLine(" You fumble getting the key into the lock, but it works!\n You open the door to find the room as if it were untouched. Strange.\n  TRY AGAIN.");
                  
                    EnterNumber();
                    return;
                    

                case "2":
                    Console.WriteLine(" You choose the second key. The door doesn't open.\n TRY AGAIN");
                    EnterNumber();
                    return;

                case "3":
                    Console.WriteLine(" You choose the second key. The door doesn't open.\n TRY AGAIN");
                    return;
            }
        }
        else if (capDoor == "KNOCK")
        {
            Console.WriteLine(" A voice behind the door speaks to you. It says, \"Answer this riddle: \"");
            Console.WriteLine(" \"Poor people have it. Rich people need it. If you eat it you die. What is it?\"");
            
        }


private void EnterNumber()
{
     Console.Write("Enter a number (1-3): ");
}

在這種情況下,如果 capDoor = "open" 並且 keyChoice = 1 或 2,我設置了要求用戶輸入數字的邏輯。但關鍵是您可以隨時要求用戶輸入數字。

這有幫助嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM