2017-03-01 109 views
1

在該項目中平均分數,我的目標是... 使用findKth 的用戶必須輸入數字(輸入查找的最高,最低,平均和平均分數 - 1停止掃描儀),他們不知道有多少,如果他們排序 但是,我看到一些問題試圖做到這一點。查找最低,最高,平均和使用findKth

我所提供的findKth方法只需要一個int [] arr,並且我無法找到一種方法來初始化一個數組,以達到此項目所需的特定大小。

有人可以建議一種方法來做到這一點?

下面是我的測試方法和我的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); 
} 

我已經嘗試了不同的方法,如試圖解析爲數字的字符串,但是我不能這樣做,因爲我無法找到一個方法來正確地停止當用戶輸入-1時的掃描儀。

另外我已經嘗試過使用ArrayList,但findKth只帶一個int [] arr。所以這是行不通的。

對此提出建議?我很難過。

回答

1

使用列表來收集輸入:

List<Integer> input = new ArrayList<>(); 

input.add(n); // add each number 

然後轉換到陣列中的所有輸入後:

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

你輸入迴路是馬車。雖然不在問題的範圍內,但請嘗試一個更簡單的循環,例如:

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

我可以使用findKth來表示平均值嗎?導致我可以告訴我只能得到高,低和中值。 –

+0

@ ConnerK.McPhee的平均值只是總和/ n。你不需要知道元素的相對位置就可以計算出來 – Bohemian