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.
CodePudding user response:
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");
}
CodePudding user response:
You can create a method to search the number and if found you can return an object of custom class Index with the row and column and if not found you can return null.
and so if this method returns null you can know number is not found and yo can print the result easily.
Creating methods and class to return index is more clean than printing the results in method, as tomorrow you can reuse the method at multiple places
public void printSearchResult() {
int[][] input2DArray = new int[0][0]; // You need to create input data here
int numberToFind = 0; // pass your number to search
Index index = findIndexOfGivenNumberIn2DArray(input2DArray, numberToFind);
if (index == null) {
System.out.println("Your number wasn't found");
} else {
input2DArray[index.getRow()][index.getColumn()] = 0;
System.out.println("Your number is in Row " index.getRow() " and Column " index.getColumn() ".");
}
}
private Index findIndexOfGivenNumberIn2DArray(int arr[][], int numberToFind) {
Index index = null;
for (int row = 0; row < arr.length; row ) {
for (int column = 0; column < arr[row].length; column ) {
if (arr[row][column] == numberToFind) {
index = new Index(row, column);
return index;
}
}
}
return index;
}
private static class Index {
private int row;
private int column;
public Index(int row, int column) {
this.row = row;
this.column = column;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}