简体   繁体   English

将精度数字加倍到数组中,然后从最低到最高对数字进行排序和显示

[英]double precision numbers into an array, then sort and display number from lowest to highest

In line 24, I am getting an error which is commented out. 在第24行中,我收到一条已注释掉的错误。 What is causing this and how to I get it fixed? 是什么原因造成的,如何解决?

Any help is much appreciated. 任何帮助深表感谢。 Thanks ahead of time. 提前谢谢。 :) :)

import java.util.Scanner;

public class main {


    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        //initialize array
        double[] numbers = new double [10];

        //Create Scanner object
        System.out.print("Enter " + numbers.length + " values: ");

        //initialize array
        for ( int i = 0; i < numbers.length; i++){
            numbers[i] = input.nextDouble() ;
            java.util.Arrays.sort(numbers[i]); //getting an error here, thay says [The method sort(int[]) in the type Arrays is not applicable for the arguments (double)]
        //Display array numbers
        System.out.print(" " + numbers);            
        }

        //Close input
        input.close();

    }


}

You need to sort the complete array rather than a single element: 您需要对整个数组而不是单个元素进行排序:

Arrays.sort(numbers);

Better to move it outside of the for -loop. 最好将其移至for循环之外。 You could use Arrays.toString to display the contents of the array itself: 您可以使用Arrays.toString来显示数组本身的内容:

for (int i = 0; i < numbers.length; i++) {
   numbers[i] = input.nextDouble();
}
Arrays.sort(numbers);
System.out.print(Arrays.toString(numbers));

Note: Class names start with an uppercase letter, eg MyMain . 注意:类名以大写字母开头,例如MyMain

Put this after the for loop: 将这个 for循环:

java.util.Arrays.sort(numbers);

notice numbers not numbers[i] and the print needs to come out of that loop too. 注意数字而不是数字[i] 并且打印也需要退出该循环。

The mistake you're making is that you are trying to sort a single number. 您犯的错误是您试图对单个数字进行排序。 The error message points out that the sort method expects an array. 错误消息指出sort方法需要一个数组。

Your algorithm should first read in all the numbers, before sorting. 您的算法应先读取所有数字,然后再进行排序。 So change your code to something like this: 因此,将您的代码更改为如下所示:

...

// first read in numbers
for ( int i = 0; i < numbers.length; i++){
    numbers[i] = input.nextDouble() ;
}

// then apply sort
java.util.Arrays.sort(numbers); // numbers is an array, so it's a valid argument.

// finally, after sorting you may now output the sorted array
for(int number : numbers){
    System.out.println(number);
}

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM