C# 当输入为int而不是double时,如何引发FormatException?
如果GPA输入为int而不是double,我必须抛出FormatException,但我不能这样做。然而,当在studentID字段中输入十进制值时,我能够抛出FormatException。我所知道的是,默认情况下,double数据类型接受int值,这就是为什么它不会引发异常,但我需要确保作为GPA输入的值是doubleC# 当输入为int而不是double时,如何引发FormatException?,c#,exception-handling,formatexception,C#,Exception Handling,Formatexception,如果GPA输入为int而不是double,我必须抛出FormatException,但我不能这样做。然而,当在studentID字段中输入十进制值时,我能够抛出FormatException。我所知道的是,默认情况下,double数据类型接受int值,这就是为什么它不会引发异常,但我需要确保作为GPA输入的值是double using System; using static System.Console; // Declare a Student // ID must be an intege
using System;
using static System.Console;
// Declare a Student
// ID must be an integer and gpa must be a double to continue
namespace Debug4_4
{
class Debug4_4
{
static void Main()
{
Student stu = new Student();
bool areNumbersGood = false;
while (!areNumbersGood)
{
try
{
stu.setID();
stu.setGPA();
areNumbersGood = true;
}
catch (FormatException e)
{
WriteLine(e.Message);
WriteLine("(Either the student ID or the GPA");
WriteLine(" was not in the correct format.)");
WriteLine("You will have to re-enter the student data.");
}
}
WriteLine("Valid student");
}
}
public class Student
{
private int stuId;
private double stuGpa;
public void setID()
{
string stuNumber;
try
{
Write("Enter student ID ");
stuNumber = ReadLine();
stuId = Convert.ToInt32(stuNumber);
}
catch (FormatException fe)
{
throw (fe);
}
}
//throw (fe);
//}
public void setGPA()
{
string stuGPAString;
//string stuGPAString;
try
{
Write("Enter student GPA ");
stuGPAString = ReadLine();
stuGpa = Convert.ToDouble(stuGPAString);
}
catch (FormatException fe)
{
throw (fe);
}
}
}
}
我认为您可以使用GetType方法
var x=10;
x.GetType(); => int
var x=10.0;
x.GetType(); => double
我假设当你说输入必须是双精度的时候,你希望输入有一个类似4.0的小数,而不是4。这是一个奇怪的要求,但如果这是你正在寻找的,那么你可以通过这样做来实现它。也许有更好的选择,但这也可以做到
if (!(Double.TryParse(stuGPAString, out stuGpa) && stuGPAString.LastIndexOf(".") < (stuGPAString.Length - 1)))
{
throw new FormatException("Invalid gpa");
};
因此,您的setGPA方法如下所示
public void setGPA()
{
string stuGPAString;
if (!Double.TryParse(stuGPAString, out stuGpa))
{
throw new FormatException("Invalid student gpa");
};
}
学生不能有4个GPA或5个GPA吗?如果用户输入的int值可以转换为double,为什么要进行这种验证?stuGpa是double。到底是什么问题?您已经声明,您认识到int可以转换为double,并且将输入存储在double字段中。所以你已经在确保输入是双精度的。闻起来像是家庭作业。与其捕获异常以检测错误,不如尝试Integer.TryParse并在失败时抛出您自己的异常。此外,如果捕获的唯一目的是抛出确切的异常,那么您实际上根本不需要try/catch块。他们什么也没做。
public void setGPA()
{
string stuGPAString;
if (!Double.TryParse(stuGPAString, out stuGpa))
{
throw new FormatException("Invalid student gpa");
};
}