我写了一个代码,它获取了一个文本文件作为输入,然后程序使用文本制作相等的String数组,这样可以比较单词并查找+计算唯一和重复的单词。该程序成功编译,但如果我尝试执行它,所以我得到问题:线程“main”中的异常java.lang.NullPointerException ... java:52。 问题必须在于我声明字符串的方式。我该怎么写呢? 谢谢!
import java.util.*;
class TextAnalyze{
public static void main(String[] args){
In read = new In ("text1.txt"); //input *.txt file
int tWords = 0; // counter, total words in the text file
int unW = 0; //counter UNIQUE words in the text file
String[] word = new String[31000]; //array with all the words
String[] word2 = new String[31000]; // array with all the words, used to compare
//String uniqueWords[] = new String[31000]; //array with the unique words
//int numberuniqueWords[] = new int [31000];
while(read.endOfFile() == false) {
word[tWords] = read.inWord();
word2[tWords] = word[tWords];
tWords++;
}
int totalWords = word.length;
int totalWords2 = word2.length;
List<String> uniqueWords = new ArrayList<>();
for (int i = 0; i < totalWords; i++) { // loop of the first array list
boolean unique = true;
for (int j = 0; j < totalWords2; j++) { // second loop where the
// words are being compared
if (word[i].equals(word2[j])) {
//we find two equals strings, it not unique
unique = false;
break;
}
}
//if it remains unique there wasn't equals
if (unique) {
uniqueWords.add(word[i]);
}
}
for (String s : uniqueWords) {
System.out.println(s);
}
}
}
答案 0 :(得分:0)
int totalWords = word.length;
这可能是你的问题。数组的长度是它的容量,而不是放在其中的实际对象数。因此,它将始终返回31000.如果这不是文本文件中的单词数,那么您的循环将从数组中提取空值。
答案 1 :(得分:0)
我认为@Aurand已经发现了这个问题。您现在可以对比较进行空检查:
if(word[i] != null && word2[j] != null){
if (word[i].equals(word2[j])) {
//we find two equals strings, it not unique
unique = false;
break;
}
}
答案 2 :(得分:0)
FileReader fr = new FileReader("/home/rajesh/Desktop/movie");
BufferedReader br = new BufferedReader(fr);
String s;
Set<String> sdata = new HashSet<String>();
List<String> adata = new ArrayList<String>();
while ((s = br.readLine()) != null) {
for (String val : s.split(" ")) {
sdata.add(val);
adata.add(val);
}
}
for (String val : sdata) {
int freq = Collections.frequency(adata, val);
System.out.println("Frequency of " + val + " " + freq);
}
如果要在命令模式下运行此代码,则必须指定try catch block或throws。
答案 3 :(得分:0)
import java.util.Vector;
import java.util.Scanner;
public class Get{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.print("enter a text? ");
String txt = in.nextLine();
Vector<Character> ch = new Vector<Character>();
char len[] = txt.toCharArray();
int count;
for(int i=0; i<len.length; i++){
count=0;
for(int j=0; j<len.length; j++){
if(len[i]==len[j]){
count++;
}
}
if(count>0){
if(!ch.contains(len[i])){
System.out.println(len[i] + " - " + count);
ch.add(len[i]);
}
}
}
}
}