0

我正在尝试打印数组对象的一个​​值。在这里,我想打印“价格为 2000 英镑”,但 2000 在对象中。如何从要打印的对象中获取 2000?

cars[7] = new Car(2000, 4, 4);
    System.out.println("Price is £"+    );

谢谢大家的帮助

4

5 回答 5

3

您需要一个返回整数的方法。

例子:

class Car {

    int price;

    public Car (int price , int i , int h) {

        this.price = price;

    }

    public int getPrice() {

        return price;

    }

}

在您的主要课程中:

System.out.println("Price is £"+ cars[7].getPrice());
于 2013-11-05T21:46:33.367 回答
1
System.out.println("Price is £"+cars[7].getPrice());

为此,您应该首先为价格编写 getter,如下所示:

public int getPrice(){
    return price;
}
于 2013-11-05T21:46:37.787 回答
1

在您的 Car 类中,有一个public int getPrice()返回汽车价格变量的方法。

于 2013-11-05T21:41:54.740 回答
1

我想您可能想查找 OO 编程。

你是如何定义汽车类的?

我会这样定义。

Class Car {
    private int firstValue;
    private int secValue;
    private int thirdValue;



    public int getfirstValue(){
        return this.firstValue;
    }
    ....

} 

因此,通过这种方式,您可以:

cars[7] = new Car(2000, 4, 4);
System.out.println("Price is £"+ cars[7].getfirstValue());
于 2013-11-05T21:44:05.460 回答
0

汽车不是数组。汽车是一个对象类型。Car 应该有一个获取值的访问方法。此外,它可以覆盖 Object.toString() 以便它返回“价格”,但这似乎是一个糟糕的 toString 实现选择。

于 2013-11-05T21:42:22.867 回答