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



这是我下面的提示:

/*
(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 );
    }
}

for (int x = 0; x < locations.length; x++)中,locations.length的值是为num_city输入的任何值...也就是说,locations.length是 2D 数组第一的大小。
x变得2(或更多(时,它对于数组的第二维来说太大了,您已经将其固定在[2]

数组从零开始,因此length==2数组具有 a[0] 和 a[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++)

内部for循环中的locations.length替换为locations[0].length

您获得数组越界异常的原因是locations.length等同于num_city。所以在你的内部循环中,你允许x一直上升到num_city,而不仅仅是直到2。

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

最新更新