Evelyn Drew Evelyn Drew - 1 month ago 13
Java Question

Not getting Required Output

I have this code below: If I call my object statement like this i get this output below:
trafficqueue.TrafficQueue$Car@1b26af3
trafficqueue.TrafficQueue$Car@8b819f

public class TrafficQueue {
private Car[] carArray;
private int numberOfcarsInQueue;
private int f = 0;

public TrafficQueue(int numberOfcarsInQueue){
carArray = new Car[numberOfcarsInQueue];


}
private static class Car {
private String make;
private String colour;

public Car(String make, String colour) {
this.make = make;
this.colour = colour;
}

public String getMake(){

return make;
}



} ;


public void add(Car car){
carArray[numberOfcarsInQueue] = car;
numberOfcarsInQueue ++;

}
public String toString()
{
String result = "";

for (int scan=0; scan < numberOfcarsInQueue; scan++)
result = result + carArray[scan].toString() + "\n";

return result;
}
public static void main(String[] args) {
// TODO code application logic here


TrafficQueue queueLane1 = new TrafficQueue(10);
Car carT = new Car("Toyota", "Red");
Car carE = new Car ("Jaguar","Red");
queueLane1.add(carT);
queueLane1.add(carE);

System.out.println(""+queueLane1.toString());
System.out.println(queueLane1);

System.out.println("Number of Cars in Queue"+ "=" + queueLane1.getNumberOfCarsInQueue());
}

}


I have tried using the java.util.arrays.toString but to no avail. whyat am I doing wrong?

Answer

The output that you're getting is produced by calling toString on the TrafficQueue object i.e. this method:

public String toString() {
    String result = "";

    for (int scan = 0; scan < numberOfcarsInQueue; scan++)
        result = result + carArray[scan].toString() + "\n";

    return result;
}

Let's examine the above method.

The above method calls carArray[scan].toString(). carArray[scan] is an instance of Car. What you're doing here is essentially calling toString on a Car.

Did you define a toString method for Car? Nope. That's why the default toString is called. That's why you see outputs like this

trafficqueue.TrafficQueue$Car@1b26af3

If you want a human readable string representation of Car, just override toString:

public String toString() {
    return colour + " " + getMake();
}

Your whole Car class should look like this:

private static class Car {
    private String make;
    private String colour;

    public Car(String make, String colour) {
        this.make = make;
        this.colour = colour;
    }

    public String getMake() {

        return make;
    }

    @Override
    public String toString() {
        return colour + " " + getMake();
    }
}