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

Java arrays help In this Lab we are going to create a utility class with static

ID: 3559154 • Letter: J

Question

Java arrays help In this Lab we are going to create a utility class with static methods to perform various operations on int arrays, much like the Arrays class in the java.util package. Our class which will be called ArrayUtil will have methods to generate a random array of a given size, print the array, find the average of the elements in the array, find how many times a number occurs in the array, sort the array, and search for a number in an array with binary or linear search. Additionally, we will have a driver class Lab8.java to test the program. This has mostly been completed for you but some additional parts need to be completed as described below. Getting Started Create a class called Lab8 and copy the given code on the class site for Lab8.java into the file. We will be adding a few lines to this later in the lab. Additionally, make another file calledArrayUtil.java. This file will be an object, so simply start it off by declaring an ArrayUtil class. Since this class is a utility class, much like the Math class or the java.util.Arrays class, we will not be creating instances of it, so it does not have a constructor (besides the default one automatically provided by Java) or instance variables. Part 1: ArrayUtil methods The ArrayUtil class provides the following static methods:

Explanation / Answer

Lab8.java

import java.util.*;
public class Lab8
{
   public static void main (String[] args)
   { // variables to hold the input
   int number, num2, num3; // variable to hold menu choice
   char command;
   Scanner keyboard = new Scanner(System.in); // print the menu
   printMenu(); // create array initialized to a default array.
   int[] array = {5, 2, 3, 8, 4, 1, 6}; // default array is not sorted so we can't use binary search
   boolean sorted = false;
  
   do { // ask a user to choose a command
       printMenu();
       System.out.println(" Please enter a command or type ?");
       command = keyboard.next().toLowerCase().charAt(0);
       switch (command)
       {
           case 'a': // generate a random array // read in size, max and min values
           System.out.print(" Please enter the size of the array: ");
           number = keyboard.nextInt();
           System.out.print("Please enter smallest number to occur in the array: ");
           num2 = keyboard.nextInt();
           System.out.print("Please enter largest number to occur in the array: ");
           num3 = keyboard.nextInt(); // input validation to make sure num3 is larger than num2.
           while (num3 < num2)
           {
               System.out.print("The largest number must be greater than " + num2 + ". Please reenter: ");
               num3 = keyboard.nextInt();
           } /* Complete code here Add code that calls the random method of the ArrayUtil class to create a new random array with size number, with min number num2 and max number num3.
               Store the result of the function call in the variable array (already declared above). */ // array no longer sorted
           array = ArrayUtil.random(number, num2, num3);
           sorted = false;
           System.out.println(" A new array was generated.");
           break;
          
           case 'b': // print the collection calling the toString method
           System.out.println(" " + ArrayUtil.toString(array));
           break;
          
           case 'c': // compute and display the average /* Complete code here Add code that call the average(int[]) method of the ArrayUtil class to print out " The average is " followed by the average. Hint: This would be similar to toString in the previous case. */
           System.out.println(" The average is "+ArrayUtil.average(array));
           break;
          
           case 'd': // compute and display the number of occurences
           System.out.print(" Enter the number you wish to find how many times it occurs: ");
           number = keyboard.nextInt(); // call occurrences(int[], int) to find the occurrences
           System.out.println(" " + number + " occurs " + ArrayUtil.occurrences(array, number) + " times.");
           break;
          
           case 'e': // search the array
               System.out.print(" Enter the number you wish to search for: ");
               number = keyboard.nextInt(); // if sorted use the more efficient binarySearch
               num2 = 0;
               if (sorted)
               {
                   num2 = ArrayUtil.binarySearch(array, number);
               }
               else
               { /* Complete code here Add code that calls the linearSearch(int[], int) method of the ArrayUtil class to find where number occurs in array.
                   Save the result in num2.
                   Hint: See the call to binarySearch in the if portion above. */
                   num2 = ArrayUtil.linearSearch(array, number);
               } // print out where number is found or if it was not
               if (num2 != -1)
                   System.out.println(" " + number + " occurs at index " + num2 + ".");
               else
                   System.out.println(" " + number + " is not in the array.");
           break;
          
           case 'f': // search for a number in the array /* Complete code here Add code that calls the selectionSort(int[]) method of the ArrayUtil class to sort the array. */
           System.out.println(" The array is sorted."); // array now sorted, so we can use binary search
           ArrayUtil.selectionSort(array);
           sorted = true;
           break;
          
           case '?': // display menu
           printMenu();
           break;
          
           case 'q': // quit
           break;
          
           default:
           System.out.println("Invalid input!");
           }
       }
       while (command != 'q');
   } //end of the main method // this method prints out the menu to a user
   public static void printMenu()
   {
       System.out.print(" Command Options " + "----------------------------------- " + "a: generate a random array " + "b: display the array " + "c: compute and display the average " + "d: compute and display the number of occurrences of a number " + "e: search the array for a number " + "f: sort the array " + "?: display the menu again " + "q: quit this program ");
   } // end of the printMenu method
}

ArrayUtil.java

import java.util.Random;

class ArrayUtil {
   public static int[] random (int size, int min, int max) {
       int []arr = new int[size];
       Random rand = new Random();
       for(int i = 0;i<size;i++){
           arr[i] = rand.nextInt(max-min+1) + min;
       }
       return arr;
   }
  
   public static double average (int[] a){
       if(a.length == 0)
           return 0.0;
       double sum=0.0;
       for(int i = 0; i<a.length;i++){
           sum += a[i];
       }
       return (double)sum / a.length;
   }
  
   public static int occurrences(int[] a, int n){
       int count = 0 ;
       for(int i = 0;i<a.length;i++){
           if(a[i] == n){
               count ++;
           }
       }
       return count;
   }
  
   public static int binarySearch(int[]a, int n){
       int start = 0;
        int end = a.length - 1;
        int mid;
        while (start <= end) {
            mid = (start + end) / 2;
            if (a[mid] == n) {
                return mid;
            } else if (a[mid] < n) {
                start = mid + 1;
            } else if (a[mid] > n) {
                end = mid - 1;
            }
        }
        return -1;
   }
  
   public static void selectionSort (int[] a){
       for (int i = 0; i < a.length - 1; i++)
        {
            int index = i;
            for (int j = i + 1; j < a.length; j++)
                if (a[j] < a[index])
                    index = j;
  
            int smallerNumber = a[index];
            a[index] = a[i];
            a[i] = smallerNumber;
        }
   }
  
   public static int linearSearch(int []a,int n){
       int pos = -1;
       for(int i = 0;i<a.length;i++){
           if(n == a[i])
               pos = i+1;
       }
       return pos;
   }
  
   public static String toString(int[] a)
   {
       String s = "["; for (int i = 0; i < a.length; i++)
       {
           if (i % 10 == 0) // print 10 elements per line
               s += " "; // add the elements formatted so they line up nicely
               s += String.format("%4d", a[i]);
       }
       return s + " ]";
   }
}

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