Я должен бросить FormatException, если GPA вводится как int вместо double, но я не могу этого сделать. Однако я смог бросить FormatException, когда десятичное значение вводится в поле studentID. Что я знаю, так это то, что по умолчанию тип данных double принимает значение int, и поэтому он не генерирует исключение, но мне нужно убедиться, что значение, введенное как GPA, двойное.
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);
}
}
}
}
stuGpa
ЯВЛЯЕТСЯ двойником. в чем именно проблема?: Вы заявили, что знаете, чтоint
может быть преобразовано вdouble
, и вы сохраняете ввод в полеdouble
. Таким образом, вы уже гарантируете, что ввод являетсяdouble
. - person Rufus L   schedule 04.10.2017catch
являетсяthrow
точное исключение, то вам вообще не нужны блокиtry/catch
. Они ничего не делают. - person Rufus L   schedule 04.10.2017