查找最低,最高,平均和使用findKth
问题描述:
在该项目中平均分数,我的目标是... 使用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。所以这是行不通的。
对此提出建议?我很难过。
答
使用列表来收集输入:
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);
}
我可以使用findKth来表示平均值吗?导致我可以告诉我只能得到高,低和中值。 –
@ ConnerK.McPhee的平均值只是总和/ n。你不需要知道元素的相对位置就可以计算出来 – Bohemian