根据用户输入的动物危险等级,calculate_insurance方法选择正确的案例,并进行计算,确定动物保险的成本。在父类中设置危险等级,在具有动态多态性的两个子类中通过重写父类进行保险计算。解决这个问题的最好方法是什么?非常感谢用您的代码进行解释。
基类-
public abstract class Animal
{
protected int danger_rating = 0;
//get danger rating from user (1-5)
while (true)
{
Console.WriteLine("What is the animals danger rating? \nSelect a number between 1 - 5: "); //Prompt user to type in animals danger rating
string input = Console.ReadLine(); //reads string input
if (int.TryParse(input, out danger_rating)) //convert user string input to int danger_rating
{
if (danger_rating == 1) //loop until danger_rating is between 1 and 5
{
break;
}
else if (danger_rating == 2)
{
break;
}
else if (danger_rating == 3)
{
break;
}
else if (danger_rating == 4)
{
break;
}
else if (danger_rating == 5)
{
break;
}
else
{
Console.WriteLine("Invalid Number. \nNumber must be between 1 - 5");
}
}
else
{
Console.WriteLine("This is not a number");
}
public virtual double calculate_insurance(int danger_rating)
{
return 0;
}
}哺乳动物类-
public class Mammal : Animal //Derived class
{
public virtual double calculate_insurance(int danger_rating)
{
int ins_base = 5000; //base for mammals
double Insurance; //this will contain the output
//Select case based on danger rating 1 - 5
switch (danger_rating)
{
case 1:
Insurance = (ins_base * 10) * 0.02;
break;
case 2:
Insurance = (ins_base * 20) * 0.05;
break;
case 3:
Insurance = (ins_base * 30) * 0.05;
break;
case 4:
Insurance = (ins_base * 40) * 0.05;
break;
case 5:
Insurance = (ins_base * 50) * 0.10;
break;
default:
Console.WriteLine("Invalid danger rating");
break;
} //end of switch
return base.calculate_insurance(danger_rating);
}
}爬行动物类-
public class Reptile : Animal //Derived class
{
public virtual double calculate_insurance(int danger_rating)
{
int ins_base = 1000; //base for reptiles
double Insurance; //this will contain the output
//Select case based on danger rating 1 - 5
switch (danger_rating)
{
case 1:
Insurance = (ins_base * 10) * 0.02;
break;
case 2:
Insurance = (ins_base * 20) * 0.05;
break;
case 3:
Insurance = (ins_base * 30) * 0.05;
break;
case 4:
Insurance = (ins_base * 40) * 0.05;
break;
case 5:
Insurance = (ins_base * 50) * 0.10;
break;
default:
Console.WriteLine("Invalid danger rating");
break;
} //end of switch
return base.calculate_insurance(danger_rating);
}
}发布于 2022-01-13 10:51:19
我不确定是否存在需要“解决”的问题,除了which循环的基类中的语法错误(在方法级别上浮动)和计算派生类型的一些保险值但随后返回基类型的保险值(即0)的一些繁琐之处。
哺乳动物和爬行动物中的calculate_insurance方法应该声明给override基本方法,并且应该以return Insurance结尾(注意:它应该被称为insurance;我们在PascalCase中不命名局部变量),不返回调用基的结果。
如果你想知道如何使用你所创造的东西。这种性质的多态背后的想法是,您可以有一个基本类型的变量,而不知道或不关心实际类型存储在其中,因为您只使用基本类型声明存在的功能
Animal a = new Mammal();
a.calculate_insurance(1); //returns 1000, the rating for a Mammal of type 1
Animal b = new Reptile();
b.calculate_insurance(1); //returns 200, the rating for a Reptile of type 1https://stackoverflow.com/questions/70694997
复制相似问题