嘿,我正在做作业,我被卡住了,我需要返回两个城市的名字,它们之间的距离最小,城市必须是在第一个城市之后的(first i,second i+1);谢谢。
public class Maincity {
public static void main(String[] args) {
City [] cityArr = new City[10];
String[] nameArr = new String[] {"Hadera","Beer Sheva","Haifa", "Ashdod", "Eilat", "Jerusalem", "Ashkelon", "Tel Aviv", "Hertzila", "Netanya"};
for (int i=0;i<cityArr.length;i++) {
int rRandom = (int)(Math.random() * 100000) + 10000;
int xRandom = (int)(Math.random() * 10000) + 1000;
int yRandom = (int)(Math.random() * 10000) + 1000;
City ir = new City(nameArr[i], rRandom, xRandom, yRandom);
System.out.println(ir);
}
System.out.println(Distance(cityArr));
}
public static int Distance(City[] city) {
int min = 100000000;
for (int i = 0; i < city.length; i++) {
int newX = city[i].getX() - city[i + 1].getX();
int newY = city[i].getY() - city[i + 1].getY();
newX = (int) Math.pow(newX, 2);
newY = (int) Math.pow(newY, 2);
int nDistance = (int) (Math.sqrt(newX) + Math.sqrt(newY));
if (nDistance < min) {
min = nDistance;
}
}
return min;
}
}发布于 2021-11-22 07:34:42
有两个问题:
您没有将城市放入数组中。ArrayIndexOutOfBoundsException抛出了
public static void main(String[] args) {
String[] nameArr=new String[] {"Hadera","Beer Sheva","Haifa", "Ashdod", "Eilat", "Jerusalem", "Ashkelon", "Tel Aviv", "Hertzila", "Netanya"};
City [] cityArr= new City[nameArr.length];
for(int i=0;i<cityArr.length;i++) {
int rRandom = (int)(Math.random()*100000)+10000;
int xRandom = (int)(Math.random()*10000)+1000;
int yRandom = (int)(Math.random()*10000)+1000;
City ir = new City(nameArr[i],rRandom, xRandom, yRandom);
cityArr[i] = ir;
System.out.println(ir);
}
System.out.println(Distance(cityArr));
}
public static int Distance(City[] city) {
int min =100000000;
for(int i=0;i<city.length;i++) {
int nextCityIndex = (i+1) % city.length;
int newX =city[i].getX() - city[nextCityIndex].getX();
int newY =city[i].getY() - city[nextCityIndex].getY();
newX = (int) Math.pow(newX, 2);
newY = (int) Math.pow(newY, 2);
int nDistance = (int) (Math.sqrt(newX)+Math.sqrt(newY));
if(nDistance<min) {
min=nDistance;
}
}
return min;
}https://stackoverflow.com/questions/70062122
复制相似问题