扫描2d数组中的下一个空值并替换行中的值

时间:2014-08-13 11:11:17

标签: java arrays multidimensional-array nested-loops

基本上,我需要搜索索引的下一个空值(指定为0),并用各种信息替换整行。例如,如果第三行中有空白元素,而不是“0,0,0,0”,则它将是“(行号),a,b,c”。这是我到目前为止,我只是得到一长串的运行时错误

String[][] clientsArray = new String[20][4];
int rows = 20;
int columns = 4;

for (int r = 0; r < rows ; r++ )
    {
        for (int c = 0; c < columns ; c++ )
            {
                if (clientsArray[r][c].equals ("0"))
                {
                    String key = Integer.toString(r);
                    clientsArray[r][0] = key;
                    clientsArray[r][0+1] = "a"
                    clientsArray[r][0+2] = "b"
                    clientsArray[r][0+3] = "c"
                    break;
                }
             }
    }

目前,整个2d数组都填充了'0',我只是没有包含那段代码。

**注意:我已将'c'的值更改为0

1 个答案:

答案 0 :(得分:1)

从评论来看,您希望:

  1. 搜索2D数组,查找第1列为“0”的第一行。
  2. 然后您想要替换该行中的每个元素。

    String[][] clientsArray = new String[20][4];
    int rows = 20; // this can also be clientsArray.length
    int columns = 4; // this can also be clientsArray[0].length
    
    for (int r = 0; r < rows ; r++ )
    {
        //since you are only looking at the 1st column, you don't need the inner loop
           // this makes sure that the spot in the 2d array is set, otherwise trying to call .equals will crash your program.
           if (clientsArray[r][0] == null || clientsArray[r][0].equals ("0")) 
           {
              String key = Integer.toString(r);
              clientsArray[r][0] = key;
              clientsArray[r][1] = "a"
              clientsArray[r][2] = "b"
              clientsArray[r][3] = "c"   //you don't need the 0+, if you wanted to have a 2d array with more then 4 rows, you could put a for loop here insead of doing it 4 times like you did here
              break; //if you wanted to find ALL empty rows take this out.
              //also note if you have 2 loops like in your question, if would only break out of the 1st one
           }   
    }