【发布时间】:2018-07-24 17:35:47
【问题描述】:
我正在做一个项目来遍历一个文本文件并输出文件中每个字母的计数。
import java.util.*;
import java.io.*;
public class frequencyAnalysis {
private static String text;
public static String alphabet;
public static int Freq[];
public frequencyAnalysis(String text) {
this.text = text;
int [] Freq = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //array of ints to keep track of how many of each letter there is.
alphabet = "abcdefghijklmnopqrstuvwxyz"; //point of reference for the program to know which number in the array should be increased
}
public static void freqAnalysis() throws IOException {
String token = "";
int index;
File subset = new File(text); //creates a new file from the text parameter
Scanner inFile = new Scanner(subset);
while(inFile.hasNext()) {
token = inFile.next();
index = alphabet.indexOf(token);
if (index == -1) { //makes sure that the character is a letter
break;
} else {
Freq[index]++;
}
}
inFile.close();
}
}
这是一个应该遍历给定文本文件的类,并计算其中每个字母的数量。
import java.util.*;
import java.io.*;
public class tester {
public static void main(String args[]) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Please type the input file path: "); //allows the user to specify a file
String input = in.next();
frequencyAnalysis Freq = new frequencyAnalysis(input);
frequencyAnalysis.freqAnalysis(); //calls the method to run through the file
for(int i = 0; i <= 25; i++){ //prints the alphabet and the Freq array
System.out.println(frequencyAnalysis.alphabet.charAt(i) + ": " + frequencyAnalysis.Freq[i]); //this is where the error is
}
}
}
这是实现类,它允许用户指定一个文件,然后运行freqAnalysis方法来调整静态Freq数组,然后打印出来。但是,当我运行程序时,它在指定行上给我一个 java.lang.NullPointerException 错误。我已经发现问题出在“frequencyAnalysis.Freq[i]”中,而不是“frequencyAnalysis.alphabet.charAt(i)”中。但是,我不知道问题是什么或如何解决。
【问题讨论】: