我的代码已接近完成,运行正常,但我希望我的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();
答案 0 :(得分:2)
您可以使用无限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);
}
}
如果输入的值不是数字(根据您的break
条件),我添加了while-loop
语句来中断if
。