问题:我该如何解决这个问题?该代码在我输入值时有效,但是当我使用扫描仪读取值时,它会在我输入城市数量并引发运行时异常后停止读取输入。
我尝试使用两个扫描仪而不是一个.. 一个用于双精度,一个用于整数,我很确定这不是您的操作方式,因为那时我看到“从双精度到整数的有损转换”。有人可以帮忙吗?仅供参考,我是一名 UX 架构师,对此我很陌生。因此,任何帮助将不胜感激。
import java.util.*;
import java.lang.Math;
public class Centralcity {
public static void main(String[] args){
int numcities;
int x = 0;
int y = 0;
double shortest = 0;
double distance1 = 0;
double distance2 = 0;
int closestX1=0, closestX2=0, closestY1 =0 , closestY2 = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of cities: " );
numcities = scanner.nextInt();
double[] xcor=new double[numcities];
double[] ycor=new double[numcities];
double[][] distance= new double[numcities][numcities];
double[] sumdistance= new double[numcities];
double[] temp= new double[numcities];
//numcities = 5;
//double xcor[]=new double[] {2.5,5.1,1,5.4,5.5};
//double ycor[]=new double[] {5,3,9,54,2.1};
for(int i = 0; i<numcities; i++)
{
for(int j = 0; j<numcities; j++)
{
System.out.println("Enter coordinates of the city:");
xcor[i]=scanner.nextDouble();
xcor[j]=scanner.nextDouble();
ycor[i]=scanner.nextDouble();
ycor[j]=scanner.nextDouble();
}
}
for(int i = 0; i<numcities; i++)
{
for(int j = 0; j<numcities; j++)
{
distance[i][j]=Math.pow((Math.pow(xcor[i]-xcor[j], 2)) + (Math.pow(ycor[i]-ycor[j], 2)), 0.5);
sumdistance[i]+=distance[i][j];
}
}
temp=sumdistance;
double temp1;
for(int i = 0; i < temp.length; i++)
{
for(int j = 1; j < (temp.length -i); j++)
{
if(temp[j-1] > temp[j])
{
temp1 = temp[j-1];
temp[j-1]=temp[j];
temp[j]=temp1;
}
}
}
double finl=0;
for(int i = 0; i <numcities; i++)
{
if(sumdistance[i]==temp[0])
{
finl=i;
}
}
System.out.println("The Central City coordinates are: " +xcor[finl]+","+ycor[finl]);
}
}