【问题标题】:Comparing values inside a 2D Array in java在java中比较二维数组中的值
【发布时间】:2015-06-13 10:49:57
【问题描述】:

我正在研究一个问题,我需要比较 Java 中二维数组中的值。例如:

int N = 2, c = 2;
int [][] arr = new int[N][c];

System.out.println("Enter the values to a 2D array: ");

for(int i=0; i<N;i++) {
    for (int j=0;j<c;j++) {
        arr[i][j]=in.nextInt();
    }     
}

所以在上面的代码中,用户在二维数组中输入值。 现在我想分别比较arr[i]&gt;=0arr[j]&gt;=0,如果是,我需要对此进行一些其他操作。

但我不能那样做。示例:

for(int i=0; i<N;i++) {
    for (int j=0;j<c;j++) {
        if (arr[i]>=0 && arr[j]>=0) {
            //Some operation//
        }
    }
}

请建议我执行此操作的方法 - 单独比较值。谢谢。

【问题讨论】:

  • 不清楚你想达到什么目的。

标签: java arrays multidimensional-array


【解决方案1】:

arr1[i] 是一个整数数组,而不是整数,所以不能将它与整数进行比较。 arr1[i][j]int,可以与整数进行比较。

if (arr[i][j]&gt;=0) 是一个有效的语法,但不清楚这是否是你想要的。

【讨论】:

  • 如何单独比较那里的值..有什么办法吗?
  • @Dev 比较什么?一个整数数组到0?这样的比较有什么意义?您希望将数组中的每个数字与 0 进行比较吗?
  • 感谢您的帮助。搞错了。
【解决方案2】:

要比较二维数组的值,您应该与该数组的每个值进行比较。

2x2 数组

。 .

。 .

当 i=0 时,j=0

x.

。 .

当 i=0,j=1

。 x

。 .

当 i=1 时,j=0

。 .

x.

当 i=1 时,j=1

。 .

。 x

   for(int i=0; i<N;i++) {
      for (int j=0;j<c;j++) {
         if (arr[i][j]>=your_comparable_value ) {
             //Some operation//
         }
      }
   }

【讨论】:

    【解决方案3】:

    您将整数存储在二维数组中。如果有帮助,您可以通过考虑行和列来对二维数组进行可视化建模 - 每个行和列对都引用它在数组中的相应存储位置。示例:

    arr[0][1] = 5; // sets the value of row [0] column [1] to 5
    

    在第二个嵌套的“for”循环(您遇到问题的那个)中,您错误地引用了二维数组的值。请记住,您必须指定要引用的对 - arr[int][int]。

    if (arr[i]>=0 && arr[j]>=0); //  incorrect way of referencing the desired respective location in the 2D array
    

    您修改后的嵌套 'for' 循环与语法准确的 'if' 语句:

    for(int i=0; i<N; i++)
        for (int j=0; j<c; j++) // side note: consider using final constant(s) replacing variables N and c. In your case, you are explicitly referencing two integers that store the same value - 2
            if (arr[i][j]>=0)
                System.out.println("Array Position [" + i + "][" + j + "] is greater than or equal to 0");
    

    【讨论】:

    • arr 不需要两个整数。 arr[i] 是一个有效的整数数组,但不能与 0 比较。
    • 感谢您的帮助。理解其背后的逻辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 2015-04-17
    • 2015-02-10
    相关资源
    最近更新 更多