需要帮助找到错误

时间:2016-02-15 00:55:50

标签: java error-handling runtime-error

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

车辆模式:飞行燃料:丙烷最高海拔高度: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;
}

}

2 个答案:

答案 0 :(得分:1)

因为你试图调用当前方法的超类版本,你需要添加super.toString()

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

您还需要与其他子类

一起执行此操作

当一个方法调用它自己的被调用的递归时,一个方法一直调用自己直到某个条件。

答案 1 :(得分:0)

这段代码会很好。问题是你多次调用toString()导致Stack溢出。另外,您必须在父类车辆中声明一个String,并在具有飞行模式等的子类中更新它。运行下面的代码:

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;
String s;
}

class HotAirBalloon extends Vehicle {

int maxAltitude;

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

class Locomotive extends Vehicle {

int horsePower;
Locomotive(int _hp) {
mode = "traversal";
fuel = "coal";
horsePower = _hp;
s= "Vehicle Mode:" + mode + " Fuel:" + fuel;

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