gpt4 book ai didi

java - 需要帮助查找错误

转载 作者:行者123 更新时间:2023-12-01 10:24:48 25 4
gpt4 key购买 nike

我有以下代码,其中包含运行时错误。该代码的目的是打印出:

车辆模式:飞行燃料:丙烷最大高度:10000

车辆模式:穿越 燃料:煤 马力:5000

我自己找不到它(因为我对编码相当陌生),并且如果可能的话希望获得一些帮助。

谢谢。

class Main {

public static void main(String[] args) {

HotAirBalloon airbag = new HotAirBalloon(10000);
Locomotive loco = new Locomotive(5000);

System.out.println(airbag.toString());
System.out.println(loco.toString());
}
}

class Vehicle {

String mode, fuel;

public String toString() {
return "Vehicle Mode:" + mode + " Fuel:" + fuel;
}
}

class HotAirBalloon extends Vehicle {

int maxAltitude;

HotAirBalloon(int _alt) {
mode = "flight";
fuel = "propane";
maxAltitude = _alt;
}
public String toString() {
return toString() + " Max Altitude:" + maxAltitude;
}

}

class Locomotive extends Vehicle {

int horsePower;
Locomotive(int _hp) {
mode = "traversal";
fuel = "coal";
horsePower = _hp;

}
public String toString() {
return toString() + " Horsepower:" + horsePower;
}

}

最佳答案

因为您正在尝试调用当前方法的父类(super class)版本,所以需要添加 super.toString()

//old
return toString() + " Horsepower:" + horsePower;
//new
return super.toString() + " Horsepower:" + horsePower;

您还需要对其他子类执行此操作

当一个方法调用自身时,它被称为递归,其中一个方法不断调用自身,直到达到某个条件。

关于java - 需要帮助查找错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35399962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com