使用用户输入的坐标查找中心城市

时间:2017-03-30 00:30:54

标签: java eclipse multidimensional-array

这是我的提示:

/*
(Central city) Given a set of cities, the central city is the city that has the
shortest distance to all other cities. Write a program that prompts the user to enter the number of
cities and the locations of the cities (the coordinates are two decimal numbers), and finds the
central city and its total distance to all other cities.
*/

出于某种原因,当我尝试运行它时,eclipse给了我这个错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2  at Testing.main(Testing.java:26)

我做了一些修修补补,当我尝试制作一个2列的二维数组时,问题就出现了。是否有一个特定的原因导致它不起作用?或者我做错了什么?提前致谢!

    import java.util.Scanner; 
    public static void main(String[] args) {
    //Declarations 
    int num_city; 
    double[][] locations; 
    Scanner keyboard = new Scanner(System.in); 

    //input 
    System.out.print("Please enter in the number of cities you want: ");
    num_city = keyboard.nextInt(); 
    locations = new double [num_city][2];       

    System.out.print("Please enter the coordinates of the cities: ");
    for (int i = 0; i < locations.length; i++)
    {
        for (int x = 0; x < locations.length; x++)
        {
            locations[i][x] = keyboard.nextDouble(); 
        }
    }

    //Output
    getCentral(locations);



    }

    //method to find the index of the central city and total distance to other cities
    public static void getCentral(double[][] array)
    {
        //declarations
        double totalDistance = 0; 
        int position = 0; 
        double cityDistance; 

        //processing
        for(int i =0; i < array.length; i++)
        {
            cityDistance = 0; 
            for (int j = 0; j < array.length; j++)
            {
                cityDistance = Math.sqrt( Math.pow( (array[j][0] - array[i][0]), 2) + Math.pow( (array[j][1] - array[i][1]), 2) );   
            }
            if ((i==0 || totalDistance > cityDistance))
            {
                totalDistance = cityDistance;
                position = i; 
            }
        }
        System.out.print("The central city is at (" + array[position][0] + ", " + array[position][1] + ")");
        System.out.println("The total distance to the other cities are :" + totalDistance );
    }

}

2 个答案:

答案 0 :(得分:0)

使用 locations.length在内部for循环中替换 locations[0].length

您获得Array Out of of bound异常的原因是locations.length等同于num_city。所以在你的内循环中,你允许x一直到num_city而不是直到2。

对于数组arr[row][col]arr.length =行但arr[i].length = col

答案 1 :(得分:0)

for (int x = 0; x < locations.length; x++)中,locations.length的值是为num_city输入的内容......也就是说,locations.length第一维的大小 of the 2d array 当x变为2(或更多)时,对于数组的第二个维度而言,它太大了,您修复了[2]

数组是从零开始的,所以length==2的数组有[0]和[1]的位置,所以当x >= 2超出范围时。

多维数组实际上是一个数组数组,因此要获得第二个维度的长度,您需要引用第一个维度中的一个数组,例如locations[0].length或者,如果在循环中,locations[i].length可行。

这在内部循环for (int j = 0; j < array.length; j++)中也很重要 同样,array.length第一个维度的大小;在这个循环中你需要for (int j = 0; j < array[i].length; j++)