无法让我的循环继续提示用户获得分数



我的代码几乎完成了,而且运行良好,除了我希望我的IF语句继续向用户询问分数。如今,它要求用户获得分数,如果您输入无效的条目,则可以让该行说说,请重试,但代码停止。我希望它继续提示用户输入无效的数字。

//Variables
            double grade;
            string studentName;
            //Prompt the user for the student's name
            Console.WriteLine("Please enter the student's name:");
            studentName = Console.ReadLine();
            //Prompt the user for the student's score
            Console.WriteLine("Please enter the student's score between 0 and 100:");
            if (!(double.TryParse(Console.ReadLine(), out grade)))
            {
               Console.WriteLine("Invalid entry, scores entered must be numeric. Please try again");
            }
            else if (grade >=90)
            {
                Console.WriteLine("{0} has a score of {1} which is an A.", studentName, grade);
            }
            else if (grade < 90 && grade >= 80)
            {
                Console.WriteLine("{0} has a score of {1} which is a B.", studentName, grade);
            }
            else if (grade < 80 && grade >=70)
            {
                Console.WriteLine("{0} has a score of {1} which is a C.", studentName, grade);
            }
            else if (grade < 70 && grade >= 60)
            {
                Console.WriteLine("{0} has a score of {1} which is a D.", studentName, grade);
            }
            else
            {
                Console.WriteLine("{0} has a score of {1} which is an F.", studentName, grade);
            }
            Console.ReadLine();

您可以使用无限while循环 -

while (true)
{
    Console.WriteLine("Please enter the student's name:");
    studentName = Console.ReadLine();
    //Prompt the user for the student's score
    Console.WriteLine("Please enter the student's score between 0 and 100:");
    if (!(double.TryParse(Console.ReadLine(), out grade)))
    {
        Console.WriteLine("Invalid entry, scores entered must be numeric. Please try again");
        break;
    }
    else if (grade >= 90)
    {
        Console.WriteLine("{0} has a score of {1} which is an A.", studentName, grade);
    }
    else if (grade < 90 && grade >= 80)
    {
        Console.WriteLine("{0} has a score of {1} which is a B.", studentName, grade);
    }
    else if (grade < 80 && grade >= 70)
    {
        Console.WriteLine("{0} has a score of {1} which is a C.", studentName, grade);
    }
    else if (grade < 70 && grade >= 60)
    {
        Console.WriteLine("{0} has a score of {1} which is a D.", studentName, grade);
    }
    else
    {
        Console.WriteLine("{0} has a score of {1} which is an F.", studentName, grade);
    }
}

i如果输入不是数字的值(根据您的if条件),则包括一个break语句,以破坏while-loop

相关内容

最新更新