基本上,我的作业需要我取一个字符串数组和一个字符串搜索词,并返回数组中搜索词的位置(如果没有找到则返回-1)并取一个字符串和气泡数组解决。我收到的错误似乎只是泡泡排序,我不明白为什么。
我收到的错误消息是:
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)
代码:
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;
}
}
答案 0 :(得分:1)
OK!我检查了你的代码,你唯一的问题是你将你的数组理解为大小为5000,这是wordPut()方法中的问题
String[] Array = new String[50000];
我在计算机上尝试了你的代码,工作正常,但是buble排序很顺利,除了数组的声明,试着找出数组的大小然后声明!