我正在尝试构建一个程序,它接收文件并输出文件中的字数。当所有的东西都在整段下面的时候,它就完美地工作了。然而,当有多个段落时,它没有考虑到新段落的第一个单词。例如,如果一个文件读到“我的名字是约翰”,程序将输出“4个单词”。但是,如果一个文件读到“我的名字是约翰”,每个单词都是一个新段落,程序就会输出"1字“。我知道这一定是关于我的if声明,但我认为在新的段落前面有空格,会考虑到新段落中的第一个单词。以下是我的代码:
import java.io.*;
public class HelloWorld
{
public static void main(String[]args)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("health.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int word2 =0;
int word3 =0;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
;
int wordLength = strLine.length();
System.out.println(strLine);
for(int i = 0 ; i < wordLength -1 ; i++)
{
Character a = strLine.charAt(i);
Character b= strLine.charAt(i + 1);
**if(a == ' ' && b != '.' &&b != '?' && b != '!' && b != ' ' )**
{
word2++;
//doesnt take into account 1st character of new paragraph
}
}
word3 = word2 + 1;
}
System.out.println("There are " + word3 + " "
+ "words in your file.");
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}我尝试过调整if语句的多个团队,但这似乎没有什么区别。有人知道我在哪里搞砸了吗?
我是一个非常新的用户,几天前我问了一个类似的问题,人们指责我对用户要求过高,所以希望这能稍微缩小我的问题范围。我真的很困惑,为什么它没有考虑到一个新段落的第一个词。如果你需要更多的信息,请告诉我。谢谢!!
发布于 2013-08-13 03:57:38
如果你的段落不是用空格开头的,那么你的if条件将不包括第一个单词。“我的名字是约翰”,程序会输出"4字“,这是不正确的,因为你错过了第一个单词,但在后面加了一个。试试这个:
String strLine;
strLine = strLine.trime();//remove leading and trailing whitespace
String[] words = strLine.split(" ");
int numOfWords = words.length;https://stackoverflow.com/questions/18200203
复制相似问题