![](/img/trans.png)
[英]How to fix “Cannot invoke ”java.awt.Point.getX()“ because ”this.p“ is null”
[英]Cannot invoke "City.getX()" because "city[i]" is null
嘿,我正在做作业,我卡住了,我需要返回两个城市的名称,它们之间的距离最小,城市必须是为了第二个在第一个之后(第一个 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;
}
}
有2个问题:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.