import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class A15 {
public static void main(String[] args) {
if(args.length != 1) {
JOptionPane.showMessageDialog(null, "Error: Enter one command line argument.");
}
else {
try {
String[] array = LeeJungBum15.readFileReturnWords(args[0]); // read file
sortAndPrintArray(array, args[0]); // sort alphabetically and print the arrays
}
catch(ArrayIndexOutOfBoundsException aobe) {
JOptionPane.showMessageDialog(null, "Error: Array is indexed out of bounds.");
}
}
} // end of main
/**
* Reads file and returns word.
* @param fileName is the String fileName
*/
public static String[] readFileReturnWords(String fileName) throws ArrayIndexOutOfBoundsException {
String[] array = new String[10000]; // declare String array
Integer index = new Integer(0); // declare Integer index
File file = new File(fileName); // read file
Scanner scan = null;
try {
scan = new Scanner(file); // scan file
}
catch(FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(null, "Error: File is not found.");
}
if(scan != null) {
while(scan.hasNext()) {
String word = scan.next(); // search words
//System.out.println(word);
array[index] = word; // store words in array
++index; // increment index
}
}
return array;
}
/**
* Sorts and prints the array.
* @param array is the String[] array
* @param fileName is the String fileName
*/
public static void sortAndPrintArray(String[] array, String fileName) throws NullPointerException {
Sorting.display = false; // prevent the automatic output of the Sorting.java program
Sorting.selectionSort(array); // sorts the String[] array
for(int i = 0; i < array.length; i++) {
if(i == 0) {
System.out.println("Alphabetical listing of words in file \"" + fileName + "\":"); // print the heading
}
else if(array[i] != null) {
System.out.println("index = " + i + ", element = " + array[i]); // print indexes and elements
}
else {
break; // terminate the program
}
}
} // end of sortAndPrintArray
} // end of class
This is supposed to take a filename from args[0], store each words as array and sort them alphabetically.
For example, if hello.txt contains these texts - B D E A C,
The output should be:
Index 0, Element A
Index 1, Element B
...
Index 4, Element E
However, I keep getting NullPointerException when Sorting.selectionSort(array) is activated.
If I comment that line out, it prints but it is not sorted.
Could anyone help me out? Thank you!