此程序使用插入排序对来自文件的前n个单词进行排序。
这不是由我做的。我们被要求使用我们的老师提供的这个程序来实现其他分类技术。我导入了源代码,当我运行它。它说:文件和插入排序。线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:0
异常线程 “main” java.lang.ArrayIndexOutOfBoundsException:0 在SortingAnalysis.main(SortingAnalysis.java:26)
但是,当我们的老师展示了它在我们班,它没有错误。
我也想知道如何从文件中排序文字,甚至没有说明文件名(例如tobesorted.txt)。也许只要它在JRE系统库中,它就可以工作,不是吗?
import java.io.*;
import java.util.*;
/**
* Compares the running times of sorting algorithms
* @author bryann
*
*/
public class SortingAnalysis {
public static void insertionSort(String[] a) {
int n = a.length;
for(int i = 1; i < n; i++) {
String cur = a[i];
int j = i - 1;
while((j >= 0) && (a[j].compareTo(cur) > 0)) {
a[j + 1] = a[j--];
} // end while
a[j + 1] = cur;
} // end for
} // end insertionSort
public static void main(String[] args) {
final int NO_OF_WORDS = 5000;
try {
Scanner file = new Scanner(new File(args[0]));
String[] words = new String[NO_OF_WORDS];
int i = 0;
while(file.hasNext() && i < NO_OF_WORDS) {
words[i] = file.next();
i++;
} // end while
long start = System.currentTimeMillis();
insertionSort(words);
long end = System.currentTimeMillis();
System.out.println("Sorted Words: ");
for(int j = 0; j < words.length; j++) {
System.out.println(words[j]);
} // end for
System.out.print("Running time of insertion sort: " + (end - start) + "ms");
} // end try
catch(SecurityException securityException) {
System.err.println("You do not have proper privilege to access the files.");
System.exit(1);
} // end catch
catch(FileNotFoundException fileNotFoundException) {
System.err.println("Error accessing file");
System.exit(1);
} // end catch
} // end main
} // end class SortingAnalysis
由于导入导致的错误?使用Eclipse,我刚按下
文件>导入>常规>文件系统>目录(他送给我们整个文件夹)>进入文件夹(我创建了一个新的项目,还有就是我“进口”代码)>完成
请帮帮我。我无法从作业开始(即在同一源文件中尝试其他排序技术),因为我无法运行它。非常感谢你!
添加了“作业”标记...您尝试过什么,可以从eclipse调试器开始。在这种情况下,你也应该发布异常堆栈跟踪,它应该告诉你异常发生的位置(行)。 – home 2012-07-08 07:35:06
谢谢,回家! – 2012-07-08 07:52:36