我对如何在 Java 中使用 Arrays.sort 感到困惑。
在我的 Java 代码中,我尝试对目录中的前 10 个文件进行排序,因此我将使用 Arrays.sort method .
首先,我创建数组来保存文件长度:
int[] sortedArray = new int[11];
稍后在我的代码中,将数字加载到排序数组后,我会这样做..
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
正确吗?谢谢
最佳答案
您正确调用了 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
循环中只有一条语句 .
关于java - 为什么我的 Arrays.sort 方法返回错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19192241/