我对于为学校项目撰写的这段代码有很多疑问。我想这样做:
创建并实现一个类层次结构,其中Vehicle超类和' Motorcycle'和卡车'是子类。
这是我粗略的代码:
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;
}
}
我尝试过尽可能多的资源,但我无法看到将数据输入超类和子类的方法,然后将信息放入一个对象(车库数组) )。另外,任何人都可以给我一些方法来打印出车库阵列对象中的数据吗?当然,如果你看到任何愚蠢的错误,请随时告诉我。 非常感谢您的帮助!
答案 0 :(得分:0)
从以下开始:
class Vehicle {
int wheels;
int weight;
public Vehicle(int wheels, int weight){
this.weight = weight;
this.wheels = wheels;
}
public int getWheels() {
return wheels;
}
public int getWeight() {
return weight;
}
}
class Truck extends Vehicle {
int payload;
public Truck(int wheels, int payload, int weight){
super(wheels, weight);
this.payload = payload;
}
public String toString() {
// todo - write code to output the truck details as a string
return "truck details here";
}
}
class Motorcycle extends Vehicle{
int passengers;
public Motorcycle(int wheels, int passengers, int weight){
super(wheels, weight);
this.passengers = passengers;
}
public String toString() {
// todo - write code to output the motorcycle details as a string
return "motorcycle details here";
}
}
您创建卡车和摩托车并将其放入车辆阵列的代码看起来很不错。
当你想要打印出来时,只需循环调用每个对象上的toString数组并打印出来:
for(Vehicle vehicle : garage) {
System.out.println(vehicle.toString());
}
此外,您测试是否charIn == 'm'
但是您创建的是卡车而不是摩托车。如果用户输入m
以外的任何内容,则可以创建摩托车。