xtremeslice
xtremeslice

Reputation: 27

Need help finding the error

I have the following code which contains a run-time error. The code was meant to print out:

Vehicle mode:flight Fuel:propane Max Altitude:10000

Vehicle mode:traversal Fuel:coal Horsepower:5000

I could not find it myself (as I am fairly new to coding) and would like some help if possible.

Thanks.

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

}

Upvotes: 0

Views: 44

Answers (2)

Adnan Temur
Adnan Temur

Reputation: 343

This code will do fine. the problem was that you were calling toString() multiple times which was causing a Stack overflow. plus you have to declare a String in parent class vehicle and update it in the child classes with flight mode etc..run the code below:

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

Upvotes: 0

Ash
Ash

Reputation: 101

Because you are trying to call the super classes version of the current method you need to add super.toString()

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

You also need to do this with your other subclass

When you a method calls itself its called recursion, where a method keeps calling itself until a certain condition.

Upvotes: 1

Related Questions