Search code examples
javaarraysmultidimensional-arraynested-loops

scanning for next empty value in a 2d array and replacing values in the row


So basically, I need to search for the next empty value of an index (which is designated as 0), and replace the whole row with a variety of information. for instance, if there is a blank element in the third row, instead of "0, 0, 0 ,0" it will be "(row number), a, b, c". This is what i have so far and i just get a long line of run-time errors

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;
                }
             }
    }

At the moment, the whole 2d array is filled with '0's, I just haven't included that section of code.

**note: i have changed the values which were 'c' to 0


Solution

  • Judging from the comments, you are looking to:

    1. search through a 2D array, looking for the first row whose 1st column is "0".
    2. Then you want to replace every element in that row.

      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
             }   
      }