Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Java, write a class with 2 methods(in addition to main) that work with 1-dime

ID: 3774493 • Letter: I

Question

In Java, write a class with 2 methods(in addition to main) that work with 1-dimensional arrays:
public static boolean same(int[]a,int b[])
same returns whether the two array args have the same size and the same values in the same order.
For example, if a holds {0} and b holds {0,0}, then same(a,b) returns false. If a holds {1,2} and b holds {2,1}, then same(a,b) returns false.
If a holds {1,1,2 } and b holds {1,2,2}, then same(a,b) returns false.
If a holds {1,2} and b holds {1,2},then same(a,b) returns true.
If a holds {} and b holds {}, then same(a,b) returns true.
public static int [] evens (int[] a)
even creates and returns an int array that has all the even elements of a. So, the returned array generally has fewer elements than a. For example, if a holds {}, then the returned array holds {}. If a holds {-2,-2,-1,-1,0,0,1,1,2,2} then the returned array holds {-2,-2,0,0,2,2}
If a holds {0,2,4,2,0}, then the returned array holds {0,2,4,2,0}. Also the returned array is not the same array as the arg array, but a separate array with the same values.

Explanation / Answer

ArrayElementsTest.java

import java.util.Arrays;


public class ArrayElementsTest {

  
   public static void main(String[] args) {
       System.out.println(same(new int[]{}, new int[]{}));
       System.out.println(same(new int[]{0}, new int[]{0,0}));
       System.out.println(same(new int[]{1,2}, new int[]{2,1}));
       System.out.println(same(new int[]{1,2}, new int[]{1,2}));
      
       System.out.println();
       System.out.println();
       System.out.println(Arrays.toString(evens(new int[]{-2,-2,-1,-1,0,0,1,1,2,2})));
       System.out.println(Arrays.toString(evens(new int[]{})));
       System.out.println(Arrays.toString(evens(new int[]{0,2,4,2,0})));
   }
   public static boolean same(int[]a,int b[]){
       if(a.length!=b.length){
           return false;
       }
       else{
           for(int i=0; i<a.length;i++){
               if(a[i] != b[i]){
                   return false;
               }
           }
           return true;
       }
   }
   public static int [] evens (int[] a){
       int evenCount = 0;
       for(int i=0; i<a.length; i++){
           if(a[i] % 2 == 0){
               evenCount++;
           }
       }
       int newarr[] = new int[evenCount];
       for(int i=0,j=0; i<a.length; i++){
           if(a[i] % 2 ==0){
           newarr[j++] = a[i];
           }
       }
       return newarr;
   }

}

Output:

true
false
false
true


[-2, -2, 0, 0, 2, 2]
[]
[0, 2, 4, 2, 0]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote