【问题标题】:How to return/print a method of multiple objects in JAVA?如何在 JAVA 中返回/打印多个对象的方法?
【发布时间】:2020-11-01 00:37:39
【问题描述】:

我对 Java 很陌生,我想知道我是否可以一次输出我的英雄和每个城市之间的距离?我要找的方法怎么看?

City city = new City();
City city1 = new City();
City city2 = new City();
City city3 = new City();
System.out.println(city.distance(hero)); // works fine for a single city = 21.1 something
System.out.println(City.noOfCitys); // works fine = 4
System.out.println(City.distances(hero)); // should output all distances at once for example as string

我的 City Class 已经使用静态 noOfCitys 计算创建的对象

package adventure;

public class City {
    
    static int noOfCitys = 0; 
    { 
        noOfCitys += 1; 
    } 
    
    private String name = "Stadt";
    private int posX = 15;
    private int posY = 15;
    
    public String getName(){
        return this.name;
    }
    
    public void setName(String name){
        this.name = name;
    }

    public int getPosX(){
        return this.posX;
    }
    
    public void setPosX(int posX){
        this.posX = posX;
    }
    
    public int getPosY(){
        return this.posY;
    }
    
    public void setPosY(int posY){
        this.posY = posY;
    }
    
    
    public String distance(Adventurer hero) {
        return ""+Math.sqrt(((this.posX-hero.getX())*(this.posX-hero.getX()))+((this.posY-hero.getY())*(this.posY-hero.getY())));
    }
}

附加信息:我已经查看了类似问题的几个答案,但不知道如何附加到我的特定问题。

【问题讨论】:

  • 创建您的新距离方法并返回您已填充距离的 String[](字符串数组)。然后你就可以在你想要使用它的数组中单步执行,并且有每一个距离。
  • 稍后再看看。谢谢你的建议!

标签: java string class methods return


【解决方案1】:

@funky 的建议(我稍微修改了一下)很有魅力。 谢谢。

        City[] city = new City[3];
        Hero hero = new Hero();
        
        city[0] = new City("Men-nefer",290,165);
        city[1] = new City("Heliopolis",262,170);
        city[2] = new City("Merimda",250,130);
        
        System.out.println(city[0].distance(hero));
        System.out.println(city[1].distance(hero));
        System.out.println(city[2].distance(hero));

【讨论】:

    猜你喜欢
    • 2010-10-02
    • 2021-06-10
    • 2016-02-01
    • 1970-01-01
    • 2014-08-02
    • 2021-02-06
    • 2012-01-24
    • 2016-02-18
    • 2021-11-30
    相关资源
    最近更新 更多