Search code examples
javaarraysfindmedian

Find Lowest, Highest, Median and Average Score using findKth


For this program, my goal is to... Find the Highest, Lowest, Median and Average Score by using findKth The user must input the numbers (Enter -1 to stop scanner) and they do not know how many there are and if they are sorted However, I am seeing some issue with trying to do this.

The findKth method I am provided only takes in an int[]arr, and I cannot find a way to initialize an array to the specific size need for this project.

Could someone suggest a way to to do this?

Below are my test methods and my findKth

import java.util.*;
 public class Statistics
  {
public static void main(String[]args)
{
    System.out.print("Enter Scores, -1 to end: ");

    Scanner keyboard= new Scanner(System.in);
    String numbers = null;

    while(keyboard.nextInt()!=-1)
    {
        numbers= keyboard.next();
    }


    String[] parts = numbers.split(" ");
    int[] n1 = new int[parts.length];
    for(int n = 0; n < parts.length; n++)
    {
        n1[n] = Integer.parseInt(parts[n]);
    }

    int highest= n1.length-1;
    int lowest=0;
    int median= n1.length/2;

    QuickSort.findKth(n1, highest);
    System.out.println("High: "+n1[highest]);
    QuickSort.findKth(n1, lowest);
    System.out.println("Low: "+n1[lowest]);
    QuickSort.findKth(n1, median);
    System.out.println("Median: "+n1[median]);

}
}

public static void findKth(int[] arr, int k)
{
            findKth(arr, 0, arr.length, k);
}
//Pre:  arr[first]..arr[last-1] contain integers
//  k must be in [first..last-1]
//Post: The elements in arr has been rearranged in such a way that arr[k] now contains the kth
//   largest element
public static void findKth(int[] arr, int first, int last, int k)
{
    int pivotLoc = rearrange(arr, first, last);
        if (pivotLoc==k) return;
        else if (pivotLoc>k) findKth(arr, first, pivotLoc, k);
        else findKth (arr, pivotLoc +1, last, k);
}

I've tried different methods such as trying to parse the string for the numbers however I cannot do this as i cannot find a way to properly stop the scanner when the user inputs -1.

Also i have tried using ArrayList, but findKth with ONLY take an int[]arr. So this will not work.

Suggestions? I am stumped.


Solution

  • Use a List to collect the input:

    List<Integer> input = new ArrayList<>();
    
    input.add(n); // add each number
    

    Then to convert to an array after all input:

    int[] array = input.stream().mapToInt(Integer::intValue).toArray();
    

    Your input loop is buggy. Although out of scope of the question, try a simpler loop, for example:

    while (true) {
        int n = keyboard.nextInt();
        if (n == -1)
            break;
        input.add(n);
    }