0

我设置了一个 10 x 10 的二维数组,每个插槽是 (x*y) 对应的位置。我正在尝试将第 3、5 和 7 列中的所有数字加到 cTotal 中,并将第 2、4 和 6 行中的所有数字加到 rTotal 中。我的编码看起来不错,但我似乎无法让它工作。有任何想法吗?

public static void arrayMath()
{
    int cTotal = 0;
    int rTotal = 0;
    //int tDiffValue = (rTotal - cTotal);

    int twodimarr[][] = new int[10][10];

    int row = 10; 
    int col = 10;
    int x = 0;
    int y = 0;

    for(x = 0; x < row; x++)
    {
        for(y = 0; y < col; y++)
        {
            twodimarr[x][y] = x*y;
        }
    }

    for(x = 0; x < row; x++)
        {
        for(y = 0; y < col; y++)
            {
            if( (x+y) < col )
            {
        //System.out.print( " " );
        }
    //System.out.print(" " + (twodimarr[x][y]));
    }
    //System.out.println();
    }

    for(x = 0; x < twodimarr.length; x++)     //Problems start down here.
      {
        for( y= 0; y<twodimarr.length; y++)
        {
            if(y == 2 || y == 4 || y == 6)
            {
            rTotal = ((rTotal + twodimarr[x][y]));
            }
        }
      }
      System.out.println("rTotal is " + rTotal + ".");

      for(x = 0; x < twodimarr.length; x++)
      {
          for(y = 0; y < twodimarr.length; y++)
          { 
             if(x == 3 || x == 5 || x == 7)
             {
             cTotal = ((cTotal + twodimarr[x][y]));
             }
          }
      }
      System.out.print("cTotal is " + cTotal + "."); 

}
4

2 回答 2

1

x==3 不是第三列,而是第四列(0,1,2,3)。这意味着它是 3*0、3*1 等列,在这种情况下 675/540 数字是正确的。

于 2013-04-01T13:53:50.453 回答
0

数组索引从 0 开始。要获得所需的行/列,您需要从要检查的数字中减去 1。对于第 2、4、6 行,检查 y == 1、3、5。对于第 3、5、7 列,检查 x == 2、4、6。

于 2013-04-01T13:56:51.510 回答