没有获得必需的输出

时间:2016-10-30 17:02:07

标签: java arrays

我有以下代码:如果我这样调用我的对象语句,我就明白了。

输出

  

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

}

我尝试使用java.util.arrays.toString,但无济于事。我做错了什么?

1 个答案:

答案 0 :(得分:0)

通过调用toString对象上的TrafficQueue来生成您获得的输出,即此方法:

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

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

    return result;
}

让我们检查上述方法。

上述方法调用carArray[scan].toString()carArray[scan]Car的一个实例。您在此处所做的主要是在toString上调用Car

您为toString定义了Car方法吗?不。这就是调用默认toString的原因。这就是为什么你会看到这样的输出

  

trafficqueue.TrafficQueue$Car@1b26af3

如果您想要一个人类可读的Car字符串表示,只需覆盖toString

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

您的整个Car课程应如下所示:

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