課堂在線Java程序設計作業求兩個數組相同元素個數

給定兩個數組(數組中不包含相同元素),求兩個數組的交集中元素的個數(即共同出現的數,如沒有則輸出爲None) 如輸入:
5
1 2 4 6 8
6
1 2 5 6 7 8

輸出: 4

import java.util.Scanner;
/*給定兩個數組(數組中不包含相同元素),求兩個數組的交集中元素的個數(即共同出現的數,如沒有則輸出爲None) 如輸入:
5
1 2 4 6 8
6
1 2 5 6 7 8
輸出: 4
*/

public class javatest003 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int num01,num02,times=0;
		System.out.println("請分別輸入兩個數組的長度:");
		Scanner in=new Scanner(System.in);
		num01=in.nextInt();
		num02=in.nextInt();
		System.out.println("請分別輸入兩個數組元素:");
		int[] array1=new int[num01];
		int[] array2=new int[num02];
		for(int N1=0;N1<num01;N1++)
		{
			System.out.println("請輸入數組1的元素:");
			array1[N1]=in.nextInt();
		}
		for(int N2=0;N2<num02;N2++)
		{
			System.out.println("請輸入數組2的元素:");
			array2[N2]=in.nextInt();
		}
		in.close();
		for(int count01=0;count01<num01;count01++)
		{
			for(int count02=0;count02<num02;count02++)
			{
				if(array1[count01]==array2[count02])
					times+=1;
			}
		}
		if(times==0)
		{
			System.out.println("兩個數組交集的交集的元素的個數爲:None");
		}else
		{
			System.out.println("兩個數組交集的交集的元素的個數爲:"+times);
		}
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章