0
package arraySort;

import java.io.IOException;
import java.io.File;
import java.util.*;

public class openFile {
    int x;
    static int i;
    static int[] myList = {100};

    public static void main(String[] args){
        try{
            File myFile = new File("arraySort.txt");
            Scanner scan = new Scanner(myFile);
            while(scan.hasNext()){                
                myList[i] = scan.nextInt();
                BubbleSort(myList);
                System.out.println(myList[i]);                                
         } 
         catch(IOException e){
             System.out.println("File not found!");
         }
    }
    public static void BubbleSort(int[] x){
        if (x[i] > x[i + 1]){
            int temp;
            temp = x[i];
            x[i] = x[i+1];
            x[i+1] = temp;
        }
    }
}
4

4 回答 4

6

这里有一些提示,而不是直接给你答案:

  1. 你没有任何循环BubbleSort()

  2. 在读取文件中的所有数字,您应该只调用BubbleSort()一次。意思是,将调用移到循环之外。while

  3. 你永远不会增加变量i,所以你只是在myList[0]每次while循环中覆盖。

  4. 数组不可调整大小。如果您尝试分配给,myList[1]否则myList[2]您将收到ArrayIndexOutOfBoundsException错误消息。有几种方法可以解决这个问题——一种是将其从 更改int[] myList = {100}ArrayList myList = new ArrayList(). 您可以使用 向其中添加数字并使用myList.add(number)查找它们myList.get(i)

于 2009-10-31T08:44:55.687 回答
2

您的程序有几个问题,不仅与排序部分有关。

static int[] myList = {100};

此行定义myList为一个大小为 1 的数组,其中包含单个元素100。然后,你的主循环是

while(scan.hasNext()) {
    myList[i] = scan.nextInt();
    BubbleSort(myList);
    System.out.println(myList[i]);
}

你不会i在这个循环中增加,所以你只是用myList你从文件中读取的任何值覆盖单个值。当你的Bubblesort函数试图访问myList[i+1]时,它会抛出一个,ArrayIndexOutOfBoundsException因为索引处没有元素i+1(等于1,因为你不增加i)。

一般来说,特别是对于初学者来说,它ArrayList比普通数组更好用。此外,您应该先填充数组,并且只有在它包含所有元素之后才尝试对其进行排序。最后,将变量设置为本地变量而不是类成员是一个更好的主意。所以这会使你的main功能类似于

ArrayList myList = new ArrayList();
while(scan.hasNext()) {
    myList.append(scan.nextInt());
}
Bubblesort(myList);

然后更改BubblesortArrayList,然后您还可以将循环索引i设置为方法本地Bubblesort。完成后,您可以着手让冒泡排序算法工作。记住要小心你的数组索引,这样你就永远不会访问数组边界之外。

于 2009-10-31T08:55:11.110 回答
1

http://www.leepoint.net/notes-java/data/arrays/32arraybubblesort.html <- 一些冒泡排序示例;)

于 2009-10-31T08:36:46.197 回答
0

改变这个:

 try{
    File myFile = new File("arraySort.txt");
    Scanner scan = new Scanner(myFile);
    while(scan.hasNext()){                
        myList[i] = scan.nextInt();
        BubbleSort(myList);
        System.out.println(myList[i]);
 } 
 catch(IOException e){
     System.out.println("File not found!");
 }

至:

try{
    File myFile = new File("arraySort.txt");
    Scanner scan = new Scanner(myFile);
    while(scan.hasNext()){                
        myList[i] = scan.nextInt();
 } 
 catch(IOException e){
     System.out.println("File not found!");
 }

 BubbleSort(myList);
 System.out.println(myList[i]);

}

根据@Federico的回答更改排序方法

于 2009-10-31T08:47:25.223 回答