0

Hey Im working on a homework and i got stuck, i need to return the name of the two citys with the least amount of distance between them, the citys must be in order that the second one is after the first one (first i, second i+1); Thanks.

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;
    }
}
Chris
  • 26,361
  • 5
  • 21
  • 42
Yonatan
  • 3
  • 5

1 Answers1

0

There were 2 problems:

  1. You didn't put the city into array.
  2. The index calculation (i+1) throwed 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;
    }
Getodac
  • 119
  • 7