C#,获取用户价值并重置它

Chr*_*s R 3 c# if-statement

现在我的问题是获得选择2来保存和重写选择中所写的内容1.选择3应该重置所有内容.现在我尝试使用if if if if仍然没有让它工作.

while (true)
{
    Console.WriteLine("\tWelcome to my program"); // Makes the user select a choice
    Console.WriteLine("[1] To write");
    Console.WriteLine("[2] To see what you wrote");
    Console.WriteLine("[3] Reset");
    Console.WriteLine("[4] End");

    string choice = Console.ReadLine();
    string  typed = ("");

    if (choice == "1") // If 1 program asks for text
    {
        Console.WriteLine("Thank you for your choice, input text"); 
        typed = Console.ReadLine(); 
    }
    else if (choice == "2") // Is supposed to say "You wrote, and what user wrote"
    {
        Console.WriteLine(typed);
    }                            
    else if (choice == "3") //  Resets the text so if 2 is selected it would say "You wrote,     "
    {
        Console.WriteLine("Reset. Would you like to try again?");
        typed = "";
    }
    else if (choice == "4") // Ends program
    {
        break;
    }
    else
    {
        Console.WriteLine("Input not computing, try again");
    }
Run Code Online (Sandbox Code Playgroud)

Fro*_*ear 5

您的问题如下.

首先,您通过循环循环整个程序while (true).一旦用户选择,程序将返回到while (true).另请注意,它string typed是在循环内定义的.因此,每次调用循环(这是所做的每个选择)时,程序都会重置'typed'的值.

要解决这个问题,请string typed在循环外部引入.

string typed = "";

while (true)
{
    //choices and stuff goes back here
}
Run Code Online (Sandbox Code Playgroud)

编辑:我注意到你//Is supposed to say "You wrote, and what user wrote的选择2的评论.请注意,选择2中的代码将不会输出"You wrote" + typed.要更正,请更改Console.WriteLine(typed);Console.WriteLine("You wrote, " + typed);.

  • 非常感谢.尝试过,现在它完美无缺 (2认同)