简体   繁体   English

打印索引和数组元素

[英]Printing index and element of array

Hey guys I'm really struggling with trying to print my array index and element value, I posted a question a few days ago and got really helpful advice but cannot seem to get this part right at all, I am able to print the 1st index of the array (distance) but not able to print the entire thing without losing the original index value: 大家好,我真的很想打印我的数组索引和元素值,我几天前发布了一个问题,得到了非常有用的建议,但似乎根本无法解决这一问题,我能够打印第一个索引数组(距离)的大小,但不能在不丢失原始索引值的情况下打印整个内容:

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);

Really sorry to keep bringing this matter up but really have tried and cannot get it to work for the life of me any help or advice would be appreciated. 真的很抱歉继续提出此问题,但实际上已经尝试过并且无法让它在我的一生中正常工作,我们将不胜感激。

First, you sort 首先,您进行排序

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;
        }
    }
}

Then, you merely print 然后,您只需打印

for (int i=0; i<distances.length; i++) {
    System.out.println(i + " -> " + distances[i]);
}

If you want to keep the original indexes, you can do that too. 如果要保留原始索引,也可以这样做。

  • the most obvious way would be to have a second paralell array, and sort that along with your original array 最明显的方法是拥有第二个paralell数组,并将其与原始数组一起排序

example: 例:

if (distances[i] < minVal) 
{
    double temp = distances[j];
    int tempindex = indices[j];
    ...
  • the better way would be to make a class with an index(or more appropriately named, an ID), and a value(which is your double), and sort an array of type Distance. 更好的方法是使一个具有索引(或更合适的名称,ID)和一个值(是您的double)的类,并对一个Distance类型的数组进行排序。

.

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM