为什么我的Arrays.sort方法返回错误?

时间:2013-10-04 23:26:45

标签: java sorting

我对如何在Java中使用Arrays.sort感到困惑。

在我的Java代码中,我正在尝试对目录中的前10个文件进行排序,因此我将使用Arrays.sort method

首先,我创建数组以保存文件长度:

int[] sortedArray =  new int[11];

稍后在我的代码中,在我将数字加载到sortedArray后,我这样做..

Arrays.sort(sortedArray);

但出于某种原因,它并不喜欢这样。我收到这个错误:

TopTen.java:46: error: <identifier> expected
        Arrays.sort(sortedArray);

以下是我的其余代码

File dir = new File("C:\\Users\\Code\\Desktop\\Work\\Oracle_Training\\Java_training\\Java_Challenge_Disk_10_files");

for(File child : dir.listFiles()){
    System.out.print(child.getName() + " " + child.length() + " , ");   
    //puting into sortedArrya
    for (int i = 0; i<11; i++){ 
        sortedArray[i] = (int)child.length();
        continue;
    }
}

int[] array = new int[10];

Random rand = new Random();
for (int i = 0; i < array.length; i++)
    array[i] = rand.nextInt(100) + 1;
System.out.println(Arrays.toString(array));

}

Arrays.sort(sortedArray);

我使用Arrays.sort正确吗?谢谢

1 个答案:

答案 0 :(得分:5)

您正在正确调用Arrays.sort(),但在第二个for循环开始后忘记了一个左大括号。换句话说,将最后一个for循环更改为:

for (int i = 0; i < array.length; i++) {
    array[i] = rand.nextInt(100) + 1;
    System.out.println(Arrays.toString(array));
}

为了防止再次发生这种情况,即使for循环中只有一个语句,您也可以养成添加大括号而不将其取出的习惯。