[英]Printing index and element of array
大家好,我真的很想打印我的數組索引和元素值,我幾天前發布了一個問題,得到了非常有用的建議,但似乎根本無法解決這一問題,我能夠打印第一個索引數組(距離)的大小,但不能在不丟失原始索引值的情況下打印整個內容:
double minVal = Double.MAX_VALUE;
int minIndex = -1;
for (int i=0, max=distances.length; i<max;i++) {
if (distances[i] < minVal) {
minVal = distances[i];
minIndex = i;
//Gets the minimum point and minimum distance
}
}
System.out.println("The Nearest to point K is point: "+minIndex+" with distance "+minVal);
真的很抱歉繼續提出此問題,但實際上已經嘗試過並且無法讓它在我的一生中正常工作,我們將不勝感激。
首先,您進行排序
for (int i=0; i<distances.length; i++) {
for(int j = i+1; j<distances.length; j++)
{
if (distances[i] > distances[j])
{
double temp = distances[j];
distances[j] = distances[i];
distances[i] = temp;
}
}
}
然后,您只需打印
for (int i=0; i<distances.length; i++) {
System.out.println(i + " -> " + distances[i]);
}
如果要保留原始索引,也可以這樣做。
例:
if (distances[i] < minVal)
{
double temp = distances[j];
int tempindex = indices[j];
...
。
Class Distance
{
public int ID;
public double value;
}
嘗試將for循環更改為for(int i=0; max = distances.length && i < max; i++){...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.