我试图让一个单独的类中的方法为我做一些数学运算,然后将结果写入控制台。我现在遇到的问题是它说对象引用没有要使用的实例。我以为我已经在调用所有其他方法的方法所在的类中较早地实例化了它,但显然有些不对劲,我不知道该怎么做才能让它工作。数学的第二部分会给我同样的错误,但如果我能解决这个问题,我应该能够轻松地解决第二个问题。
class FruitGarden
{
private Apple apple;
private Banana banana;
static void Main(string[] args)
{
FruitGarden fruitGarden = new FruitGarden();
fruitGarden.EatFruits();
}
public void MakeFruits()
{
Apple apple = new Apple();
apple.apple(1.5);
Banana banana = new Banana();
banana.banana(3.5);
}
public void EatFruits()
{
double dblpercent;
MakeFruits();
Console.WriteLine("You have an Apple and a Banana in your fruit garden.\n");
Console.WriteLine("What Percent of the Apple would you like to eat?");
dblpercent = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("\nWhat Percent of the Banana would you like to eat?");
dblpercent = Convert.ToDouble(Console.ReadLine());
Console.Write("You have ");
apple.Eat(dblpercent);
Console.Write("% of your apple, and ");
banana.Eat(dblpercent);
Console.Write("% of your banana left.");
Console.ReadLine();
}
}
它试图引用的苹果类是:
class Apple : Fruit
{
public double Radius { get;set;}
public void apple(double radius)
{
Radius = Radius;
}
}
我以为苹果apple = new Apple();
会制作它需要的实例,但显然不是?