Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package HWPres5;
- import java.util.Scanner;
- public class array3Val {
- //This function receive two array of type integer and merge them to get a third one
- //has the same values with a count for the number that match.
- public static int[] mergetwoArray (int[] arrOne, int[] arrTwo){
- int [] equals = new int[Math.min(arrOne.length, arrTwo.length)];
- int count=0;
- for(int i:arrOne){
- for(int j: arrTwo){
- if(i==j){ // if the values in index are equal, Array Equals created
- equals[count]=i;
- count+=1;
- }
- }
- }
- return makeThird(equals,count);
- //call for make new function to create an array of the proper length
- // the count allow me to only add the right values no empty indexs
- }
- // Function that gets an array and the number of items in it
- public static int[] makeThird (int[] arrOne,int howMany){
- int[] merged= new int[howMany];
- for(int i=0; i<howMany; i+=1){
- merged[i]=arrOne[i];
- }
- return merged; // Return a third array with only the values equal to count
- }
- //This function gets an array and converts it to Sting array
- public static String intToString (int[] merged){
- String str="";
- for(int i: merged){
- str+=i+" ";
- }
- return str;
- }
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- //Created 3 arrays of type integer and intilized their size to be
- //allow future changes int change control the size
- int elements1=0, elements2=0, elements3=0;
- int[] arr3 = new int[elements3];
- System.out.printf(" Please, Enter the Numbers of elements in your FIRST array? ", elements1);
- elements1 = scan.nextInt();
- int[] arrOne= new int[elements1] ;
- //Read the prompted values into the Arrays
- System.out.printf(" Please, Enter %d Elements in your First Array:%d", elements1,arrOne.length);
- for (int i = 0; i < arrOne.length; i++) {
- arrOne[i] = scan.nextInt();}
- System.out.printf(" Please, Enter the Numbers of Elements in your SECOND array? ", elements2);
- elements2 = scan.nextInt();
- int[] arrTwo= new int[elements2];
- System.out.printf(" Please, Enter %d Elements in Second Array:%d ",elements2,arrTwo.length);
- for (int j = 0; j < arrTwo.length; j++){
- arrTwo[j] = scan.nextInt();
- }
- // creates the third array by calling function mergeTwoArray
- arr3 = mergetwoArray(arrOne, arrTwo); // create a third array arr3 with equal digits in arr1 and arr2
- System.out.println(" The Digits Equal in both arrays after the merge are "+intToString(arr3));
- // After calling Function convert integer to String
- //print the third array with the results if any!
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement