【发布时间】:2014-10-07 04:20:39
【问题描述】:
以下是我必须完成的 Java 程序的说明和代码。我被卡住了,不知道如何继续。我试图弄清楚这一点。我觉得我不知道我在做什么。非常感谢所有帮助、指导和解释。
编写一个名为
Car的类,该类具有以下字段:
yearModel:yearModel字段是一个包含汽车年份模型的 int。
make:make字段引用了一个保存汽车品牌的字符串对象。
speed:speed字段是保存汽车当前速度的 int。此外,该类应具有以下构造函数和其他 方法:
构造函数:一个构造函数应该接受汽车的年份模型, 制作和速度作为论据。这些值应分配给 对象的
yearModel、make和speed字段。另一个构造函数将 没有参数,并将分配 0 作为汽车的年份型号和速度 和一个空字符串(“”)作为品牌。访问器:适当的访问器方法应该获取存储的值 在对象的
yearModel、make和speed字段中。Mutators:适当的 mutator 方法应该将值存储在一个 对象的
yearModel、make和speed字段。
accelerate: 加速方法应该在speed字段中添加 5 每次调用。
brake:刹车方法应该从speed字段中减去5 调用它的时间。在要求用户输入数据的程序中演示该类 然后创建一个
Car对象。然后它调用accelerate方法 五次。每次调用accelerate方法后,获取当前 汽车的speed并显示它。然后调用brake方法五 次。每次调用brake方法后,获取当前speed的 汽车并展示它。运行此程序的输出将类似于:
Enter the car's year model: 1965 Enter the car's make: Mustang Enter the car's speed: 30 Current status of the car: Year model: 1965 Make: Mustang Speed: 30 Accelerating... Now the speed is 35 Accelerating... Now the speed is 40 Accelerating... Now the speed is 45 Accelerating... Now the speed is 50 Accelerating... Now the speed is 55 Braking... Now the speed is 50 Braking... Now the speed is 45 Braking... Now the speed is 40 Braking... Now the speed is 35 Braking... Now the speed is 30
这是我目前所拥有的:
public class Car {
// Declaration of variables.
private int yearModel;
private String make;
private int speed;
// Constructor that accepts arguements.
public static void acceptor(int yearModelIn, String makeIn, int speedIn){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the car's year model: ");
yearModelIn = keyboard.nextInt();
System.out.println("Enter the car's make: ");
makeIn = keyboard.next();
System.out.println("Enter the car's speed: ");
speedIn = keyboard.nextInt();
}
// Constructor that zeroes fields.
public void zeroer()
{
yearModel = 0;
speed = 0;
make = ("");
}
// Accessor Methods
public int getYearModel()
{
return yearModel;
}
public String getMake()
{
return make;
}
public int getSpeed()
{
return speed;
}
// Accelerate method for adding 5 to speed.
public void Accelerate()
{
speed += 5;
}
// Brake method for reducing speed.
public void Brake()
{
speed-=5;
}
【问题讨论】:
-
Accessor只是getter方法的一个花哨词,而Mutator- 对于setter。 -
"我卡住了" 用什么?哪个部分不工作?
-
你的构造函数应该看起来像
public Car(String whatever){}而不是“接受者”或“归零者” -
如果您不知道
Constractor是什么以及它的用途,您需要回到您的书籍/课堂笔记。
标签: java constructor accessor mutators