Reputation: 27
Scanner input = new Scanner(System.in);
int numInput;
int number[][] = {
{10, 20, 30},
{15, 25, 35},
};
System.out.print("\n\tEnter a Number : ");
// Expected input 10
numInput = input.nextInt();
input.nextLine();
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (numInput == number[i][j]) {
System.out.print("\n\tNumber " + numInput + " Found!");
System.out.print("\n\tOn line " + i + " Column " +j);
} else {
System.out.print("\n\tNumber Not Found!");
}
}
}
If the user enters 35, this program will print "Number 35 Found!" for the number found in the array or "Number not Found!" for every other element in the array.
I want it to print this only once.
Upvotes: 0
Views: 42
Reputation: 1581
It looks like you need to move the print statement for "Number not Found" outside of your for loops. Like this:
Scanner input = new Scanner(System.in);
int numInput;
int number[][] = { {10, 20, 30},
{15, 25, 35},
};
System.out.print("\n\tEnter a Number : ");
//Expected input 10
numInput = input.nextInt();
input.nextLine();
boolean found = false;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (numInput == number[i][j]) {
found = true;
System.out.print("\n\tNumber " + numInput + " Found!");
System.out.print("\n\tOn line " + i + " Column " +j);
}
}
}
if (!found) {
System.out.print("\n\tNumber Not Found!");
}
The way you have it now, it is always going to either print Found or Not Found, for every item. But if you only want it to print once at the end, you'll need to have some sort of flag to determine if it was found, and if not, then print.
Upvotes: 2