Skip to content
Advertisement

Trying to read a 2D Array for a Value and Display its Location. Encountering Issue Delivering a message when it isn’t found

I am reading through a 2D Array and when it displays every instance of the target integer to find, I can’t seem to find a way for the nested for loop to display a message Number not found or something like this.

The 2D Array has 8 Rows and 9 Columns.

Here is the program below:

  for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
      if (arr[i][j] == intRequest){
        System.out.println("Your number is in Row " + (i) + " and Column " + (j) + ".");
                              
                                
        arr[i][j] = 0;
                         
        i = 10;
                                
        break;
                                
                                
      }                          
    }
  }

When it can’t find the number, it just prints nothing which is better than an error but I can’t seem to figure out a way to display that confusion of the program.

I have tried counting the number of times the number shows up until there are none left to then display that message when it is equal to the total number of times that number shows up. This stil doesn’t work oddly.

Advertisement

Answer

You could try creating a flag and setting to true once you find your number. If it is still false by the end of the loops then you haven’t found the number. I haven’t tested the code but it should look something like this.

boolean found = false;
for (int i = 0; i < arr.length; i++) {
  for (int j = 0; j < arr[i].length; j++) {
    if (arr[i][j] == intRequest) {
      System.out.println("Your number is in Row " + (i) + " and Column " + (j) + ".");
      arr[i][j] = 0;
      found = true;
      break;
    }                           
  }
}

if (!found) {
  System.out.println("Your number wasn't found");
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement