我正在尝试对文本文件使用几种排序方法。我可以让filereader
工作,但它不能对arrays
. 当我在没有它的情况下手动完成时,filereader
它确实有效。在这里,我使用了简单的冒泡排序,因为它已经手动工作但现在不会了。
这是我的代码:
public class BubbleSort {
public static void main(String[] args) throws Exception {
File f=new File("filename.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
ArrayList alist = new ArrayList();
String s = br.readLine();
while (s != null)
{
alist.add(Integer.parseInt(s));
s = br.readLine();
}
int[] iArray = new int[alist.size()];
for (int i = 0; i < alist.size(); i++)
iArray[i] = (int) alist.get(i);
System.out.println(alist + " ");
bubbleSort(iArray);
printarray(iArray);
fr.close();
}//end loop
public static void bubbleSort(int[] alist) {
int outer, inner;
for (outer = alist.length - 1; outer > 0; outer--) { // counting down
for (inner = 0; inner < outer; inner++) { // bubbling up
if (alist[inner] > alist[inner + 1]) { // if out of order...
int temp = alist[inner]; // ...then swap
alist[inner] = alist[inner + 1];
alist[inner + 1] = temp;
}
}
}
}
public static void printarray (int []alist){
for (int i = 0; i < alist.length;i++){
System.out.println("" + alist);
}
}
}