首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法调用"City.getX()“,因为"city[i]”为空

无法调用"City.getX()“,因为"city[i]”为空
EN

Stack Overflow用户
提问于 2021-11-22 07:15:50
回答 1查看 52关注 0票数 0

嘿,我正在做作业,我被卡住了,我需要返回两个城市的名字,它们之间的距离最小,城市必须是在第一个城市之后的(first i,second i+1);谢谢。

代码语言:javascript
复制
public class Maincity {
    public static void main(String[] args) {
        City [] cityArr = new City[10];
        String[] nameArr = new String[] {"Hadera","Beer Sheva","Haifa", "Ashdod", "Eilat", "Jerusalem", "Ashkelon", "Tel Aviv", "Hertzila", "Netanya"};

        for (int i=0;i<cityArr.length;i++) {
            int rRandom = (int)(Math.random() * 100000) + 10000;
            int xRandom = (int)(Math.random() * 10000) + 1000;
            int yRandom = (int)(Math.random() * 10000) + 1000;
            City ir = new City(nameArr[i], rRandom, xRandom, yRandom);
            System.out.println(ir);
        }

        System.out.println(Distance(cityArr));
    }

    public static int Distance(City[] city) {
        int min = 100000000;

        for (int i = 0; i < city.length; i++) {
            int newX = city[i].getX() - city[i + 1].getX();
            int newY = city[i].getY() - city[i + 1].getY();
            newX = (int) Math.pow(newX, 2);
            newY = (int) Math.pow(newY, 2);
            int nDistance = (int) (Math.sqrt(newX) + Math.sqrt(newY));

            if (nDistance < min) {
                min = nDistance;
            }
        }

        return min;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-11-22 07:34:42

有两个问题:

您没有将城市放入数组中。ArrayIndexOutOfBoundsException抛出了

  1. (i+1)

代码语言:javascript
复制
    public static void main(String[] args) {
        String[] nameArr=new String[] {"Hadera","Beer Sheva","Haifa", "Ashdod", "Eilat", "Jerusalem", "Ashkelon", "Tel Aviv", "Hertzila", "Netanya"};
        City [] cityArr= new City[nameArr.length];
        for(int i=0;i<cityArr.length;i++) {
            int rRandom = (int)(Math.random()*100000)+10000;
            int xRandom = (int)(Math.random()*10000)+1000;
            int yRandom = (int)(Math.random()*10000)+1000;
            City ir = new City(nameArr[i],rRandom, xRandom,  yRandom);
            cityArr[i] = ir;
            System.out.println(ir);
        }
        System.out.println(Distance(cityArr));
    }
    public static int Distance(City[] city) {
        int min =100000000;
        for(int i=0;i<city.length;i++) {
            int nextCityIndex = (i+1) % city.length;
            int newX =city[i].getX() - city[nextCityIndex].getX();
            int newY =city[i].getY() - city[nextCityIndex].getY();
            newX = (int) Math.pow(newX, 2);
            newY = (int) Math.pow(newY, 2);
            int nDistance = (int) (Math.sqrt(newX)+Math.sqrt(newY));
            if(nDistance<min) {
                min=nDistance;
            }

        }
        return min;
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70062122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档