这是我下面的提示:
/*
(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