我该怎么写这个,所以程序在用户输入他的名字后重新启动

问题描述 投票:-3回答:1

程序要求输入名称,我希望程序在生成随机数后询问用户是否想要再次执行此操作。如果用户按Y,程序应重新启动。

 while (true) { 
            Random rnd = new Random();
            int trust = rnd.Next(0, 100);            
            Console.WriteLine("Tell me your name");
            string name = Console.ReadLine();
            Console.WriteLine(name +" " + "is" + " " + trust + " " + "points `enter code here`trustworthy");



            if (trust <= 20)
            {
                Console.WriteLine("gtfo");
            }

            if (trust >= 21 && trust <= 50)
            {
                Console.WriteLine("not gonna tell you anything");
            }

            if (trust >= 50 && trust <= 70)
            {
                Console.WriteLine("not that trustworthy");
            }

            if (trust >= 71 && trust <= 90)
            {
                Console.WriteLine("quite trustworthy");
            }

            if (trust >= 91 && trust <= 100)
            {
                Console.WriteLine(" you are trustworthy");
            }
            Console.ReadKey();
            Console.WriteLine("\nAgain? (y/n)");
            if (Console.ReadLine().ToLower() != "yes")
                    break;
            }
c#
1个回答
1
投票

您可以在代码中修复一些问题。

  1. 循环的退出条件(你调用break;的地方)应该是如果用户没有输入“是”(如果他们输入“是”,你就会中断)。
  2. 如果您只想要询问用户名,请将该部分取出
  3. 您应该只声​​明一个Random实例,而不是在每次循环迭代中实例化一个新实例,因此我们也可以将其从循环中取出。
  4. 您可以使用else if,因为条件都是独占的 - 如果我们点击一​​个true,则无需处理所有其他条件
  5. 您可以使用string interpolation使输出字符串更具可读性
  6. 我们可以允许用户使用Console.ReadKey输入“y”而不是“yes”

这些实现的东西看起来像:

Console.WriteLine("Tell me your name");
string name = Console.ReadLine();
Random rnd = new Random();

while (true)
{
    int trust = rnd.Next(0, 100);
    Console.WriteLine($"{name} is {trust} points trustworthy");

    if (trust <= 20) Console.WriteLine("gtfo");
    else if (trust <= 50) Console.WriteLine("not gonna tell you anything");
    else if (trust <= 70) Console.WriteLine("not that trustworthy");
    else if (trust <= 90) Console.WriteLine("quite trustworthy");
    else Console.WriteLine("you are trustworthy");

    Console.WriteLine("\nAgain? (y/n)");

    if (Console.ReadKey().Key != ConsoleKey.Y) break;
}
© www.soinside.com 2019 - 2024. All rights reserved.