繁体   English   中英

无法调用“City.getX()”,因为“city[i]”是 null

[英]Cannot invoke "City.getX()" because "city[i]" is null

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

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;
    }
}

有2个问题:

  1. 你没有把城市排列起来。
  2. 索引计算 (i+1) 抛出 ArrayIndexOutOfBoundsException
    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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM