下面的代碼讓我錯誤的解決問題的辦法。我知道問題在於雙倍距離設置爲0.我不知道如何解決這個問題。我會喜歡任何解決方案,因爲我已經呆了好幾個小時了。我試過設置 公共靜態雙距離; 並移動公式一下。
我想把5個地方的座標加在一起。
import java.util.Scanner;
class distance {
public static void main(String[] args) {
System.out.println("Welcome to Travel Bliss Distance Calculator!");
Scanner input = new Scanner(System.in);
int[] x = new int[5];
int[] y = new int[5];
String[] city = new String[5];
int i=0;
for (i=0; i < 5;){
System.out.println("Enter City>>");
city[i] = input.next();
System.out.println("Enter X Coordinates>>");
x[i] = input.nextInt();
System.out.println("Enter Y Coordinates>>");
y[i] = input.nextInt();
System.out.println("You Entered: " + city[i] + " with Coordinates: (" + x[i] + "," + y[i] + ") ");
i++;
}
System.out.println("============================================================");
System.out.println("Total Distance Between:" + city[0] +", " + city[1] + ", " + city[2] + ", " + city[3] + ", " + city[4]+" is>>");
System.out.println(totalDistance(x, y, i));
}
public static double totalDistance(int[] x, int[] y, int i){
double distance = 0;
if (i == 1){
double cordX = x[i] - x[i-1];
double cordY = y[i] - y[i-1];
distance = Math.pow(cordX , 2) + Math.pow(cordY, 2);
return distance;
}
else {
return Math.round(Math.sqrt(distance) + totalDistance(x,y,i-1));
}
}
}
這功課嗎?請標記爲這樣。如果是這樣,請解釋您嘗試過的以及您卡在哪裏。你有沒有在調試器中完成程序? – 2011-06-15 03:16:16
你的for循環是草率的:刪除'int i = 0;'(for循環之前的行 - 這什麼都不做)並且將'i ++'移動到'for(for i = 0; i <5; i ++)' – Bohemian 2011-06-15 03:25:14
您需要計算每個城市之間的距離還是兩個終點城市之間的最終距離? – 2011-06-15 03:37:24