Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package myApp;
- import java.util.Scanner;
- public class class05_03 {
- /*public final static int SIZE = 5;*/
- //isIn() method, accepts 2 args: 1st int, 2nd int array
- //if the method locates the number inside the array, return true, otherwise return false
- public static boolean isIn(int number, int arr[]) {
- for (int test: arr) {
- if (test == number) { return true; }
- }
- return false;
- }
- //newArr() method, accepts 2 args: 1st int array, 2nd int array
- public static int[] newArr(int arr1[], int arr2[]) {
- /*int newArr[] = new int[SIZE];*/
- int newArr[] = new int[arr1.length];
- int newIndex = 0;
- //loop through arr1
- for (int number1: arr1) {
- //for each iteration of arr1, loop through arr2
- for (int number2: arr2) {
- //compare systematically every item from arr1, with every item from arr2
- if (number1 == number2 && !(isIn(number1, newArr))) {
- //if condition holds true,
- //update new array with item, and raise new array's index count by 1
- newArr[newIndex] = number1;
- newIndex += 1;
- }
- }
- }
- return newArr;
- }
- public static void main(String[] args) {
- //init vars
- final int SIZE = 5;
- int[] arr1 = new int[SIZE],
- arr2 = new int[SIZE],
- arr3;
- //open in_stream
- Scanner s = new Scanner(System.in);
- //populate array #1
- System.out.printf("Enter %d numbers: ", arr1.length);
- for (int i=0; i<arr1.length; i+=1) {
- arr1[i] = s.nextInt();
- }
- s.nextLine(); //eat 'Enter', disregard it
- //populate array #2
- System.out.printf("Enter %d numbers: ", arr2.length);
- for (int i=0; i<arr2.length; i+=1) {
- arr2[i] = s.nextInt();
- }
- s.nextLine();
- s.close(); //close in_stream
- //assemble array #3
- arr3 = newArr(arr1, arr2);
- //print array #3
- System.out.print("New array: ");
- for (int number: arr3) {
- System.out.printf("%d - ", number);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement