我是java的新手,我需要创建一个存储数字的数组,然后在排序列表中输出平均模式和中位数。
任何人都可以告诉我,到目前为止我是否在正确的轨道上使用下面的代码
int number=0;
ArrayList<Integer> listOfNumbers = new ArrayList<>();
Scanner scannerStream = new Scanner (System.in);
System.out.println("Enter list of numbers to Sort: (OR * TO END LIST)");
while(!(listOfNumbers = br.readLine()).equals("*"))
{
listOfNumbers = scannerStream.nextInt();
NumberList = listOfNumbers();
public Vector listOfNumbersSort(int number){
for (int i=0; i<NumberList; i++) {
int Sort = listOfNumbers();;
return Sort;
// returns the mean
public Vector<Integer> listOfNumbersMean (int number){
return mean;
} // end
// returns the mode
public Vector<Integer> listOfNumbersMode (int number){
return mode;
} // end
// returns the median
public Vector<Integer> listOfNumberMedian (int number){
return median;
} // end
提前感谢您提供任何建议的帮助
答案 0 :(得分:1)
使用Collections.sort()
对ArrayList
进行排序。
使用Arrays.sort()
对数组进行排序。
答案 1 :(得分:0)
can anyone tell me if I am on the right track so far with the code below
您的方法定义看起来不太好。您正在传递一个数字并期望sortedlistofnumbers。当然,如果你已经有了一个列表,并对它进行了排序,然后如果你得到一个新的数字并需要重新排序,那么你可以按照你所写的方法签名,但不能在初级层面。
您接受号码列表的方式不对。你需要一个循环。当你使用数组时,由于数组是固定长度的,你也应该指定大小。
请参阅以下代码以供参考。
如果你想以自己的方式实现排序,有各种算法,如冒泡排序。
排序数组
public class Sorter {
public static void main(String[] args) {
Scanner scanner = new Scanner(new InputStreamReader(System.in));
System.out.println("How many numbers to sort ?");
int count = scanner.nextInt();
int numbers[] = new int[count];
System.out.println("Enter list of numbers to Sort: ");
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
numbers[i] = scanner.nextInt();
}
System.out.println("List before sorting..");
for (int i = 0; i < count; i++) {
System.out.println(numbers[i]);
}
Arrays.sort(numbers);
System.out.println("Sorted list");
for (int i = 0; i < count; i++) {
System.out.println(numbers[i]);
}
}
}
对ArrayList进行排序
public class SorterList {
public static void main(String[] args) {
Scanner scanner = new Scanner(new InputStreamReader(System.in));
System.out.println("How many numbers to sort ?");
int count = scanner.nextInt();
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter list of numbers to Sort: ");
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
numbers.add(scanner.nextInt());
}
System.out.println("List before sorting..");
System.out.println(numbers);
Collections.sort(numbers);
System.out.println("Sorted list");
System.out.println(numbers);
}
}
修改强>
如果你想进行自定义排序 - 比如冒泡排序算法,
int temp;
for (int i = 0; i < (count - 1); i++) {
for (int j = 0; j < count - i - 1; j++) {
if (numbers[j] > numbers[j + 1]) // '> for ascending order'
{
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}