0

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.");

       }

     }

   }

 }

2 Answers 2

3

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.");
}
Sign up to request clarification or add additional context in comments.

2 Comments

You guys are awesome. It works and actually makes alot of sense now.
Pleasure that we can help someone...:)
1
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");

  }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.