gpt4 book ai didi

java - 从另一个方法访问对象信息

转载 作者:行者123 更新时间:2023-12-02 05:20:51 26 4
gpt4 key购买 nike

我有一个程序,但我不明白如何在另一种方法中访问一个特定对象的信息。这是我的程序的一个小样本,我想在同一个类(称为 Cyclist)中创建此方法骑手。我想打印出这里的骑手列表,但我不明白如何...

public void riders() {
//System.out.print(c1.getName())
//this does not work.
//here I want to print out all the names of the riders, i.e. c1's name, c2's name... cn...

}



public void abilities() {

//Pardilla blir til!
Cyclist c1 = new Cyclist();

c1.setName("Sergio Pardilla");
c1.setMountain(75);
c1.setTimeTrial(60);
c1.setSprint(60);
c1.setAge(30);

System.out.println(c1.getName() + "'s abilities:");
System.out.println("Mountain - " + c1.getMountain());
System.out.println("TimeTrial - " + c1.getTimeTrial());
System.out.println("Sprint - " + c1.getSprint());
System.out.println("Age - " +c1.getAge());

}

最佳答案

您在 riders() 方法中看不到 c1 变量。c1在能力()内部声明,然后是它的本地变量,仅在内部可见。如果你想在这个方法之外使用变量,你应该使用一个字段而不是局部变量,或者将它作为参数传递给rider方法。

List<Cyclist> cyclists = new ArrayList<>(); // Declared as field

public void riders() {
for (cyclist : cyclists){
System.out.print(cyclist.getName())
}
}



public void abilities() {

//Pardilla blir til!
Cyclist c1 = new Cyclist();

c1.setName("Sergio Pardilla");
c1.setMountain(75);
c1.setTimeTrial(60);
c1.setSprint(60);
c1.setAge(30);

System.out.println(c1.getName() + "'s abilities:");
System.out.println("Mountain - " + c1.getMountain());
System.out.println("TimeTrial - " + c1.getTimeTrial());
System.out.println("Sprint - " + c1.getSprint());
System.out.println("Age - " +c1.getAge());

cyclists.add(c1); //Add cyclist to cyclists list
}

关于java - 从另一个方法访问对象信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26526897/

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