[英]Analysing text that is read from a file in Java
我正在编写一个程序,用于分析输入的文本并计算平均字母数。 当用户输入文本时,我可以使用它,但是当从文件中读取文本时,它不能使用。
public static void ReadFromFile() throws IOException {
String filename = "name.txt";
String str = new String(new char[100]);
try{
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
while ((str = br.readLine()) !=null) {
System.out.println(str + "\n");
}
br.close();
} catch(IOException e) {
System.out.println("File not found");
}
while (c != str.length()) {
if (str.charAt(c) >= 'a' && str.charAt(c) <= 'z') {
count[str.charAt(c) - 'a']++;
}
c++;
}
for (c = 0; c<26;c++){
if (count[c] !=0){
double num = count[c];
double denom = str.length();
double average = num / denom;
System.out.print((char) (c + 'a') + " occurs " + count[c] + " times in the entered string. Average is ");
System.out.println(average);
}}}}
我不断收到错误消息,说
Exception in thread "main" java.lang.NullPointerException
at MainMenu.ReadFromFile(MainMenu.java:79)
at MainMenu.main(MainMenu.java:25)
任何帮助将不胜感激谢谢
您正在逐行读取整个文件,并将其打印到System.out
完成此操作之后,您可以尝试处理数据,但是您已经完成了文件的读取,因此str为'null'并且程序终止。
在代码的早期,您具有以下循环:
while ((str = br.readLine()) != null) {
System.out.println(str + "\n");
}
当str
不为null
时,这将从文件中读取行。
这意味着当它停止时, str
为 null
。
由于在此之后不给str
提供非null
值,因此在稍后的代码中尝试在str
上运行方法时,会得到NPE:
while (c != str.length()) { // str is null here!
if (str.charAt(c) >= 'a' && str.charAt(c) <= 'z') {
count[str.charAt(c) - 'a']++;
}
c++;
}
通过查看您的代码,我的猜测是您想收集有关文件中每一行的信息。 为此,不仅要打印每行,还需要在读取文件的循环内移动计数逻辑:
// read each line from the file
while ((str = br.readLine()) != null) {
System.out.println(str + "\n");
// collect character data for this line
while (c != str.length()) {
if (str.charAt(c) >= 'a' && str.charAt(c) <= 'z') {
count[str.charAt(c) - 'a']++;
}
c++;
}
}
然后,像已经在做的一样,稍后在代码中处理count数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.