gpt4 book ai didi

java - 如何从数组中检索对象属性信息

转载 作者:行者123 更新时间:2023-12-01 11:48:15 25 4
gpt4 key购买 nike

我正在尝试获取汽车对象的速度。实际上,所有汽车都存储在一个数组中,然后将该值传递给另一个变量。

这是我所拥有的一个例子:

public class Car
{
private int speed;

public Car(int s)
{
speed = s;
}

public int getSpeed()
{
return speed;
}
public void setSpeed(int s)
{
speed = s;
}
}

我有一个类可以创建一系列汽车。

public class Environment {

private Car[] garage;
private Random random;


public Environment(){
random = new Random();
populateGarage();
}

public void populateGarage()
{
garage = new Car[4];
int randomSpeed;
Car car;

for(int i= 0; i < garage.length; i++)
{
randomSpeed = random.nextInt(10);
if(randomSpeed < 5){
randomSpeed = randomSpeed +5;
}
car = new Car(carNames[i], randomSpeed);
garage.add(car);

System.out.println("car has speed "+ car.getSpeed());
}

到目前为止一切正常。现在我试图在不同的类中访问该值。这是一个例子:

public class RaceDisplay extends JPanel implements ActionListener{

private int velX;
private int x;
private Car car;
private Environment env;


public RaceDisplay(){

x=0;
velX=env.getArray[0]... (the velocity value should be one of the car's speeds) <-------------
}

public void paintComponent(Graphics g){

super.paintComponent(g);
// (....)

}
public void actionPerformed(ActionEvent e) {

x=x+velX;
if(x>=650){
x=0;
x=x+velX;
}
}

我陷入了如何通过另一个类访问该信息的困境。非常欢迎任何帮助。

最佳答案

因为garage是一个私有(private)字段,您需要在Environment中设置一个getter函数

public Car getGarage (int index) {
return garage [index];
}

当然,如果您对 Car 对象根本不感兴趣,而只想要速度,您可以为其编写一个方法,例如:

public int getSpeedOfCar (int index) {
return garage [index].getSpeed ();
}

关于java - 如何从数组中检索对象属性信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com