我正在尝试创建一个程序,您可以在其中输入int的值,然后使用方法在该整数中添加或减去数字“10”。问题在于我写的时候:Console.WriteLine("After addition, your value is now {0}",CustomClass.CustomClass'Method);
编译器告诉我,我无法将对象转换为方法。
这是我的代码:
public class CarClass
{
public static string carModel;
public static int carSpeed;
public static void Accelerate()
{
carSpeed = carSpeed + 10;
}
public static void Brake()
{
carSpeed = carSpeed - 10;
}
}
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Enter car model: ");
CarClass.carModel = Console.ReadLine();
Console.WriteLine("Enter initial speed: ");
CarClass.carSpeed = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Starting speed of {0} is {1} km/h.", CarClass.carModel, CarClass.carSpeed);
Console.WriteLine("Now some speed changing...");
Console.WriteLine("After accelerating, new speed of {0} is {1} km/h.",CarClass.carModel,CarClass.carSpeed + CarClass.Accelerate); // here the speed should be starting speed + 10
Console.WriteLine("After accelerating, new speed of {0} is {1} km/h.",CarClass.carModel,CarClass.carSpeed + CarClass.Accelerate); //here the speed should be the previous speed + 10
Console.ReadLine();
}
}
}
我不确定这是否是正确的加速方式,因为我需要它来存储先前的值然后再添加“10”。 如果你帮我解决这个问题,我会非常感谢你们。 提前谢谢。
答案 0 :(得分:3)
您的问题是这个表达式:
CarClass.carSpeed + CarClass.Accelerate
carSpeed
是一个整数,Accelerate
是一种方法。你不能将数字和方法加在一起,它没有任何意义。
您要做的是执行该方法,该方法将更新carSpeed
。然后你可以打印carSpeed
的值。如下所示:
CarClass.Accelerate();
Console.WriteLine("After accelerating, new speed of {0} is {1} km/h.",
CarClass.carModel, CarClass.carSpeed);