如何正确使用if ... else语句和for循环?

时间:2019-04-21 23:42:26

标签: arrays loops for-loop if-statement

我有两个数组。我必须显示两个数组,然后在其中找到公用整数。如果有,请显示它们。如果没有显示0或写出输出

我有for循环来做,但是由于else在循环内,所以它循环了该语句。我将如何使其仅显示该语句一次?顺便说一句,没有通用的整数,因此该语句可以正确显示...只是出于某种原因而循环。

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

1 个答案:

答案 0 :(得分:1)

使用此代码

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