这是我用C#编写的简单和新手程序。我刚尝试过整数,但是当我尝试自然输入时,它会抛出一个execption。我想知道如果发生任何字符串输入而不抛出异常,如何警告用户。 (PS:我是一个荒谬的初学者)。
float quiz, mid, final,avg;
Console.WriteLine("Enter quiz score:");
quiz= float.Parse(Console.ReadLine());
Console.WriteLine("Enter mid-term score:");
mid = float.Parse(Console.ReadLine());
Console.WriteLine("Enter final score:");
final = float.Parse(Console.ReadLine());
avg=(quiz+mid+final)/3;
while (avg<=100 && quiz<=100&& mid <=100 && final<=100 )
{
if (avg >= 90)
Console.WriteLine("Grade A");
else if (avg >= 70 && avg < 90)
Console.WriteLine("Grade B");
else if (avg >= 50 && avg < 70)
Console.WriteLine("Grade C");
else if (avg < 50)
Console.WriteLine("Grade F");
else
Console.Write("invalid operation!!");
break;
}
while (avg > 100)
{
Console.WriteLine("Please enter the right scores!");
//Console.ReadLine();
break;
}
while (mid > 100)
{
Console.WriteLine("Please enter the right scores!");
//Console.ReadLine();
break;
}
while (final > 100)
{
Console.WriteLine("Please enter the right scores!");
//Console.ReadLine();
break;
}
while (quiz > 100)
{
Console.WriteLine("Please enter the right scores!");
//Console.ReadLine();
break;
}
Console.ReadLine();
答案 0 :(得分:1)
你可以试试这个:
bool isNumeric;
int i = -1;
string str = Console.ReadLine();
isNumeric = int.TryParse(str, out i);
if(isNumeric == false)
Console.WriteLine("Not an integer");
取自here
答案 1 :(得分:0)
我刚刚实现了&#34; isNumeric&#34;解决方案并遇到整数定义问题因为我使用浮点类型变量。我重新安排并修改了我的代码。这是最后一个正常工作版本:
bool isNumeric;
float i;
string str;
string name = "";
float quiz=0;
float mid=0;
float final=0;
float avg=0;
Console.WriteLine("Please enter your name:");
name = Console.ReadLine();
while (true)
{
Console.WriteLine("Enter quiz score:");
str = Console.ReadLine();
isNumeric = float.TryParse(str, out i);
if (isNumeric)
{
quiz = float.Parse(str);
if (quiz>100)
{
Console.WriteLine("Please enter the right scores!");
}
else
{
break;
}
}
else
{
Console.WriteLine("Not an integer");
}
}
while (true)
{
Console.WriteLine("Enter mid-term score:");
str = Console.ReadLine();
isNumeric = float.TryParse(str, out i);
if (isNumeric == false)
{
Console.WriteLine("Not an integer");
}
else
{
mid = float.Parse(str);
if(mid>100)
{
Console.WriteLine("please input the right score");
}
else
{
break;
}
}
}
while (true)
{
Console.WriteLine("Enter final score:");
str = Console.ReadLine();
isNumeric = float.TryParse(str, out i);
if (isNumeric == false)
{
Console.WriteLine("Not an integer");
}
else
{
final = float.Parse(str);
if (final > 100)
{
Console.WriteLine("Please enter the right scores!");
}
else
{
break;
}
}
}
avg = (quiz + mid + final) / 3;
while (avg <= 100 && quiz <= 100 && mid <= 100 && final <= 100)
{
if (avg >= 90)
Console.WriteLine(name+" 's Grade is A");
else if (avg >= 70 && avg < 90)
Console.WriteLine(name+ " 's Grade is B");
else if (avg >= 50 && avg < 70)
Console.WriteLine(name+ "Grade C");
else if (avg < 50)
Console.WriteLine("Grade F");
else
Console.Write("invalid operation!!");
break;
}
Console.ReadLine();