Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Jessica Wong
- * Create an ArrayStat class with a private instance variable that is of type int array. Create a constructor that initializes this variable. Write code for four methods:
- * 1) Create a sorted copy of the private instance array by using a loop.
- * 2) Create a sorted copy of the private instance array by using the Arrays class copy method.
- * 3) Find the median of the private instance array by calling on a sorted copy method. DO NOT ALTER THE ORIGINAL ARRAY.
- * 4) Find the mode of the private instance array by calling on a sorted copy method. DO NOT ALTER THE ORIGINAL ARRAY.
- * TEST YOUR CODE IN THE MAIN CLASS
- */
- import java.util.*;
- public class Main {
- public static void main(String[] args) {
- int test[] = {3,5,2,5,6,1,7,1,5,7,6,3,7,8,8,9,2,1,12,4,1,5,23,24};
- ArrayStat obj = new ArrayStat(test);
- System.out.print("Sorted array:\n");
- for (int x = 0; x < test.length; x++)
- {
- System.out.print(obj.SortArray()[x]);
- if (x != test.length-1)
- {
- System.out.print(",");
- }
- }
- System.out.println("");
- for (int y = 0; y < test.length; y++)
- {
- System.out.print(obj.ArraySortLoop()[y]);
- if (y != test.length-1)
- {
- System.out.print(",");
- }
- }
- System.out.println("\nMedian:\n" + obj.theMedian() + "\nMode:\n" + obj.findMode());
- }
- }
- ----------------------------------------------------------------------
- import java.util.*;
- public class ArrayStat {
- private int arr[];
- public ArrayStat (int x[]) {
- arr = x;
- }
- public int[] ArraySortLoop(){
- int arrlen = arr.length;
- int ara[] = new int[arrlen];
- for (int x = 0; x < arrlen; x++)
- {
- ara[x] = arr[x];
- }
- Arrays.sort(ara);
- return ara;
- }
- public int[] SortArray() {
- int ara[] = new int[arr.length];
- System.arraycopy(arr,0,ara,0,arr.length);
- Arrays.sort(ara);
- return ara;
- }
- public double theMedian() {
- int[] ara = SortArray();
- int length = ara.length;
- if (ara.length%2 == 1)
- {
- return ara[length/2];
- }
- else
- {
- double sum = ara[length/2] + ara[length/2 + 1];
- return sum/2;
- }
- }
- public int findMode() {
- int ara[] = SortArray();
- int count = 0;
- int maxcount = 0;
- int tempmode = ara[0];
- int mode = ara[0];
- for (int x = 0; x < ara.length; x++)
- {
- tempmode = ara[x];
- count = 0;
- for (int y = x; y < ara.length; y++)
- {
- if (tempmode == ara[y])
- {
- count++;
- }
- if (count > maxcount)
- {
- maxcount = count;
- mode = tempmode;
- }
- }
- }
- return mode;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement