2D数组 - 指定新的2d数组的数量

时间:2017-04-16 17:37:38

标签: java arrays multidimensional-array

我有一个2-d数字的双数字,它是48乘48,我试图制作一个允许用户选择特定数量的方法,例如= 7乘7然后将其放入一个新的2d数组。

public static double[][] amountOTP(double [][] a, int x){
    a = new double[x][x];
    return a;
}

这就是我现在所拥有的,这需要一个2d数组作为输入,但即使我指定了x它也不起作用。

6 个答案:

答案 0 :(得分:2)

很抱歉,如果我错了,但我现在假设您希望您的方法返回一个较小的2d数组,其中包含给定数组的某些值,在这种情况下,您需要将方法更改为这样:

public static double[][] amountOTP(double [][] a, int x) {
   double[][] b = new double[x][x];
   x = Math.min(x, a.length);
   for(int i = 0;i < x; i++)
      for(int j = 0;j < x; j++)
         b[i][j] = a[i][j];
   return b;
}

这应该可以正常工作,但如果我遗漏了任何内容或者它不起作用,请随时发表评论并通知我;我在这里帮忙。无论如何,我希望这适合你。 (另外,如果这不是你想要的答案,请随时告诉我。)

注意:这应该避免IndexOutOfBounds例外,因此如果用户提供的x值大于a的大小,它仍然可以正常工作。此方法返回的2d数组只有一些零值,无法找到任何数字。

答案 1 :(得分:2)

下面的解决方案考虑了所请求的新二维数组长度大于原始数据的情况,在这种情况下我们只返回原始数据。

示例:

public static double[][] amountOTP(double [][] a, int x){
       if(x > a.length) return a;
       for (double[] arr : a)
          if(arr.length < x)
             return a;

       double[][] newArray = new double[x][x];
       for (int i = 0; i < x; i++)
          for (int j = 0; j < x; j++)
             newArray[i][j] = a[i][j];

       return newArray;
}

答案 2 :(得分:2)

如果你想将它切割成较小的尺寸并复制原始阵列的一部分,这应该有效:

public static double [][] cutArray (double [][] a, int newSize){
  if (x > a.length)
     throw new IllegalArgumentException ("Can only make array smaller");
  double [][] b = new double [newSize][newSize];
  for (int i = 0; i < newSize; i++){
    for (int j = 0; j < newSize; j++){
      b [i][j] = a [i][j];
    }
  }
  return b;
}

答案 3 :(得分:1)

我认为这就是你要找的东西:

public static double[][] amountOTP(double [][] a, int x){
    double [][] ret = new double[x][x];

    for(int i = 0; i < x; i++)
        for(int j = 0; j < x; j++)
            ret[i][j] = a[i][j];
    return ret;
}

但是你必须小心参数,因为它可能导致IndexOutOfBounds异常

答案 4 :(得分:0)

你实际上还没有初始化数组,所以方法应该是这样的

function searchAttorneys() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("search-attorneys");
  filter = input.value.toUpperCase();
  table = document.getElementById("attorneys");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    tds = tr[i].getElementsByTagName("td");
    var found = false;
    for (j = 0; j < tds.length; j++) {
      td = tds[j];
      if (td) {
        if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
          found = true;
          break;
        }
      }
    }
    if (found) {
      tr[i].style.display = "";
    } else {
      tr[i].style.display = "none";
    }
  }
}

答案 5 :(得分:0)

我看到你已经有了很多答案,但没有人使用优秀的Arrays.copyOf Java API方法:

public static double[][] amountOTP(double [][] a, int x){
    a = Arrays.copyOf(a, x);
    for(int i=0; i<a.length; i++) {
        if(a[i] != null) {
            a[i] = Arrays.copyOf(a[i], x);
        } else {
            a[i] = new double[x]; // allows growth
        }
    }
    return a;
}
相关问题