Reputation: 11
Basically, I have homework that requires me to take an array of strings and a string search term, and return the position of the search term in the array (or -1 if not found)and take an array of strings and bubble sort it. I am getting an error with what seems to only be the bubble sort and I have no idea why.
The error message I'm getting is:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String$CaseInsensitiveComparator.compare(String.java:1193)
at java.lang.String$CaseInsensitiveComparator.compare(String.java:1186)
at java.lang.String.compareToIgnoreCase(String.java:1239)
at mmtextreader.MMTextReader.bubbleSort(MMTextReader.java:100)
at mmtextreader.MMTextReader.main(MMTextReader.java:47)
Code:
public class TextReader {
/**
* @param args the command line arguments
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
String[] Array;
Array = wordPut("beowulf.txt");
Scanner reader = new Scanner(System.in);
System.out.println("Input word: ");
String term = reader.next();
int position = pFind(Array, term);
if(position == -1) {
System.out.println("no word found");
} else {
System.out.println(term + " is found at " + (position+1));
}
bubbleSort(Array);
}
public static String[] wordPut(String s) throws FileNotFoundException {
String[] Array = new String[50000];
Scanner reader = new Scanner(new BufferedReader(new FileReader(s))).useDelimiter("[^\\p{Alpha}']+");
int wordcount = 0;
while (reader.hasNext()) {
Array[wordcount] = reader.next();
wordcount++;
}
for (int i = 0; i < Array.length; i++) {
if (Array[i] != null) {
System.out.println(Array[i]);
}
}
return Array;
}
public static String[] bubbleSort(String[] a) {
int lElement = a.length - 1;
boolean t = true;
for (int i = 0; i <= a.length - 1; i++) {
boolean swap = false;
for (int j = 0; j < lElement; j++) {
if (a[j].compareTo(a[j + 1]) > 0) {
String store = a[j];
a[j] = a[j + 1];
a[j + 1] = store;
swap = true;
}
}
lElement--;
if (swap == false) {
break;
}
}
for(int n = 0; n < a.length; n++) {
System.out.println(a[n]);
}
return a;
}
public static int pFind(String[] a, String trm) {
int pos = -1;
for (int i = 0; i < a.length; i++) {
if (a[i].compareToIgnoreCase(trm) == 0) {
pos = i;
break;
}
}
return pos;
}
}
Upvotes: 0
Views: 133
Reputation: 518
OK! I checked your code and the only problem you have is you inicialize your array to have size of 5000 which is the problem in wordPut() method
String[] Array = new String[50000];
I tried on my computer your code, works fine, also the buble sort is going well, except that declaration of array, try to find out the size of array and then declare!
Upvotes: 1