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 回答
这里有一些提示,而不是直接给你答案:
你没有任何循环
BubbleSort()
。在读取文件中的所有数字后,您应该只调用
BubbleSort()
一次。意思是,将调用移到循环之外。while
你永远不会增加变量
i
,所以你只是在myList[0]
每次while
循环中覆盖。数组不可调整大小。如果您尝试分配给,
myList[1]
否则myList[2]
您将收到ArrayIndexOutOfBoundsException
错误消息。有几种方法可以解决这个问题——一种是将其从 更改int[] myList = {100}
为ArrayList myList = new ArrayList()
. 您可以使用 向其中添加数字并使用myList.add(number)
查找它们myList.get(i)
。
您的程序有几个问题,不仅与排序部分有关。
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);
然后更改Bubblesort
为ArrayList
,然后您还可以将循环索引i
设置为方法本地Bubblesort
。完成后,您可以着手让冒泡排序算法工作。记住要小心你的数组索引,这样你就永远不会访问数组边界之外。
改变这个:
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]);
}