Reputation: 93
I'm trying to solve a problem where I need to find all the even numbers only. I need to input 5 numbers, and if none of the numbers are even I want to print Even number not found in array. So my problem is when I iterate through the for-loop, my code prints Even number not found in array. It prints for each non-even number, which is not what its suppose to do obviously. I need some kind of hint. This is not homework btw, it is a problem found on Programmr.com. Here is my code:
import java.util.Scanner;
public class ArrayEven {
public static void main(String args[]) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int x, arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
if (i == 4)
break;
}
for (int i = 0; i < arr.length; i++) {
x = arr[i] % 2;
if (x == 0) {
System.out.println(arr[i]);
}
else if (x != 0) { //this is obviously wrong. Do I need another for-loop for this?
System.out.println("Even number not found in array.");
}
}
}
}
Upvotes: 0
Views: 62
Reputation: 3212
public static void main(String args[]) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int x, arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
if (i == 4)
break;
}
boolean evenFound = false;
for (int i = 0; i < arr.length; i++) {
x = arr[i] % 2;
if (x == 0) {
System.out.println(arr[i]);
evenFound = true;
}
}
if(!evenFound){
System.out.println("Not found");
}
}
Upvotes: 1
Reputation: 4314
You can use a boolean
here,
Initialize boolean
variable with false
if you found any even
than set the boolean
as true
and check that boolean
in your if
condiion.
Example :
boolean isAvailble = false;
...
// Some code
...
for (int i = 0; i < arr.length; i++) {
x = arr[i] % 2;
if (x == 0) {
System.out.println(arr[i]);
isAvailble = true;
}
}
if (! isAvailable) {
System.out.println("Even number not found in array.");
}
Upvotes: 3