-1
对于我为学校项目编写的这段代码,我有很多问题。我试图这样做:Java层次结构和对象数组
创建和实现一个类的层次结构,其中Vehicle超类和'摩托车'和'卡车'是子类。
- 摩托车和卡车的共同点是变量车轮和重量以及方法显示()。这些属性不应该在课堂外访问。 display()将打印出轮子和重量,只能通用于普通类和所有的子类。
- 摩托车级别独有的数据应该是乘客。 Truck类独有的数据应该是有效载荷。包含显示此信息的方法。
- 绘制类层次结构。
- 创建一个'驱动程序'类来测试您的层次结构。允许用户通过将引用存储在Vehicle数组中来创建多个对象。您应该允许用户通过输入'm'来创建摩托车对象,然后询问相关属性。沿着相同的路线,使用't'来创建卡车对象。
- 输入完所有数据后,通过调用display()方法打印出每个对象的内容。在卡车的情况下打印摩托车或载荷的人数。需要注意的是display()方法将被覆盖了不同的子类
这里是我的代码原油:
import java.util.Scanner;
class Hierarchy{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Vehicle [] garage = new Vehicle [3];
for(int i = 0; i< garage.length;i++){
System.out.println("Please enter 't' to create a truck, and 'm' for a motorcycle");
String charIn = in.nextLine();
if(charIn == "m"){
System.out.println("What is the payload of the Truck");
int payload = in.nextInt();
System.out.println("What is the weight of the Truck");
int weight = in.nextInt();
System.out.println("How many wheels does the Truck have");
int wheels = in.nextInt();
garage[i] = new Truck(payload, wheels, weight);
}else{
System.out.println("How many passengers can the Motorcycle seat");
int passengers = in.nextInt();
System.out.println("What is the weight of the Motorcycle");
int weight = in.nextInt();
System.out.println("How many wheels does the Motorcycle have");
int wheels = in.nextInt();
garage[i] = new Motorcycle(passengers, weight, wheels);
}
}
//display();
}
}
class Vehicle{
int wheels;
int weight;
public Vehicle(int wheels, int weight){
weight = this.weight;
wheels = this.wheels;
}
//private void display(int weight, int passengers, int wheels){
//}
//private void display(int weight, int payload, int wheels){
//}
}
class Truck extends Vehicle{
int payload;
public int getWheels(){
return wheels;
}
public int getWeight(){
return weight;
}
public Truck(int wheels, int payload, int weight){
super(wheels, weight);
this.payload = payload;
}
}
class Motorcycle extends Vehicle{
int passengers;
public int getWheels(){
return wheels;
}
public int getWeight(){
return weight;
}
public Motorcycle(int wheels, int passengers, int weight){
super(wheels, weight);
this.passengers = passengers;
}
}
我在尽可能多的资源试图寻找周围尽我所能,但我看不到将数据输入到超类和子类中的方法,然后将信息放入一个对象(车库数组)中。另外,任何人都可以给我一些方法来打印车库数组的对象中的数据?当然,如果你看到任何愚蠢的错误,随时告诉我。 非常感谢您的帮助!
为了很好地打印数组,'Arrays.toString(someArray)'是你的朋友。 – azurefrog