This program sorts the first n words from a file using insertion sort.
This is not made by me. We were asked to use this program our teacher provided to implement other sorting techniques. I imported the source code and when I run it. It says:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 0
at SortingAnalysis.main(SortingAnalysis.java:26)
But when our teacher demonstrated it in our class, there is no error in it.
I’m also wondering how it sorts the words from a file without even stating the file name (e.g. tobesorted.txt). Maybe as long as it’s within the JRE System Library, it will work, won’t it?
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
Is the error because of import? Using Eclipse, I just clicked
File > Import > General > File System > From directory (the whole folder he sent to us) > Into folder (I created a new project and there is where I “imported” the code) > Finish
Please help me. I can’t start with the assignment (that is, trying other sorting techniques in the same source file) because I can’t run it. Thank you very much!
The main function of a program takes arguments :
Those arguments are the ones passed to the program on the command line :
In this case,
args[0]would be"/home/somebody/tobesorted.txt"This enables the program to know what file to open :
But when you launch your program without providing the path to a file, args is too short and you have this
java.lang.ArrayIndexOutOfBoundsException: 0 as args[0] doesn't existyou got.So give the path to the file to sort to remove this error. For example :
EDIT:
If you want to hardcode the path, you may do this :
(note the double
\\).