【问题标题】:How do I copy part of a row of a 2d array into a 1d array?如何将 2d 数组的一行的一部分复制到 1d 数组中?
【发布时间】:2021-12-19 16:42:20
【问题描述】:

我有一个充满天气数据的double 二维数组。每行的格式相同,前两个数字是位置的经度和纬度,行的其余数字是该位置的实际天气数据。我应该如何查找特定行并仅将行的索引 1 之后的剩余数字复制到一维数组中(基本上忽略前两个索引)?

到目前为止我试过了:

int x = 0; //index for new 1d array
   for(int i = 0; i <= weather.length; i++) {
        for(int j = 0; j < weather[i].length; j++) {

//checks if this row's data is for the correct location
            if(weather[i][j] == longitude && weather[i+1][j+1] == latitude) {

/* if the current element is the latitude, that means all of the values after the ith 
index is the relevant data and can be copied into the new 1d array*/ 
                data[x] = weather[i+1][j+1];
                x++;
            }
        }
    }

但这显然行不通。我似乎无法理解这样做的逻辑。如有任何反馈,我将不胜感激

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    您使用元素索引访问特定行:

    double[] specificRow = weather[index];
    

    您使用 Arrays.copyOfRange 之类的东西复制索引 1 之后的所有内容:

    double[] copy = Arrays.copyOfRange(specificRow, 2, specificRow.length);
    

    【讨论】:

    • 有没有办法在不导入Arrays的情况下做到这一点?
    【解决方案2】:

    实现中似乎有几个错误:

    • i &lt;= weather.length - 可能导致ArrayIndexOutOfBoundsException
    • (weather[i][j] == longitude &amp;&amp; weather[i+1][j+1] == latitude) - 比较不同行的数据;还应使用阈值来比较双打。

    如果Arrays.copyOfRange由于某些原因无法使用,则应该这样获取副本数组:

    // utility method to compare doubles
    static boolean doubleEquals(double d1, double d2) {
        return Math.abs(d1 - d2) < 1e-10d;
    }
    
    
    double[] row = null;
    
    for (int i = 0; i < weather.length; i++) {
        if (doubleEquals(weather[i][0], longitude) 
         && doubleEquals(weather[i][1], latitude )) {
            row = new double[weather[i].length - 2];
            for (int j = 0; j < weather.length; j++) {
                row[j] = weather[i][j + 2];
            }
            // or just row = Arrays.copyOfRange(weather[i], 2, weather[i].length);
            break; // row found
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      相关资源
      最近更新 更多