Dimination
Dimination

Reputation: 9

How to properly use if...else statement in conjunction with a for loop?

I have two arrays. I have to display both arrays and then find common integers within them. If there are any, display them. If there aren't display 0 or write an outpu

I have the for loops to do it, but since the else is within the loops, it loops that statement. How would I make it so it only displays that statement once? By the way, there are no common integers so that statement is displayed correctly... just looped for some reason.

static void PrintF(int[] MyNumbers, int[] OtherNumbers) {
  System.out.println("");
  System.out.println("The first array's numbers are "+(Arrays.toString(MyNumbers))+" and the second array's numbers are "+(Arrays.toString(OtherNumbers))+".");

     for(int i = 0; i < MyNumbers.length; i++) {
            for(int j = 0; j < OtherNumbers.length; j++) {
                if(MyNumbers[i] == OtherNumbers[j]) {
                    System.out.println(MyNumbers[i]);
                }
                else {
                  System.out.print("There are no common intergers between MyNumbers and OtherNumbers.");
            }
        }
   }
}

Upvotes: 0

Views: 36

Answers (1)

A Farmanbar
A Farmanbar

Reputation: 4798

use this code

  static void PrintF(int[] MyNumbers, int[] OtherNumbers) {
  System.out.println("");
  System.out.println("The first array's numbers are "+(Arrays.toString(MyNumbers))+" and the second array's numbers are "+(Arrays.toString(OtherNumbers))+".");
     boolean has = false;
     for(int i = 0; i < MyNumbers.length; i++) {
            for(int j = 0; j < OtherNumbers.length; j++) {
                if(MyNumbers[i] == OtherNumbers[j]) {
                    System.out.println(MyNumbers[i]);
                    has=true;
                }
            }
        }
        if(!has)
        {
         System.out.print("There are no common intergers between MyNumbers and OtherNumbers.");
        }
      }
  }

Upvotes: 1

Related Questions