这是我的提示:
/*
(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 );
}
}
答案 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++)