我需要读取一个文件并检查每个单词后面是否跟着某些“两个单词”,例如约翰·史密斯先生。因此,当我阅读文件时,当我面对“先生”这个词时,我应该检查“先生”后面的两个单词,看看它们是否是“约翰·史密斯”,并计算这种情况发生的次数。我写了下面的程序
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream ("TestF.txt"));
String line=reader.readLine();
HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
while(line!=null)
{
String[] tokens= line.split(" ");
for (int i=0; i<tokens.length; i++)
{
if tokens[i].equals("Mr.")
{
if(!(tokens[i+1].isEmpty()))
{
if (tokens[i+1].equlas("John")
String s= "John";
else
s= "Other Name";
}
else
s="";
if(!(tokens[i+2].isEmpty()))
{
if (tokens[i+1].equlas("Smith")
String s2= "Smith";
else
s2= "Other Name";
}
else
s2="";
if (s.equals("John")&&s2.equals("Smith"))
{
if (wordCount.containsKey(tokens[i]))
wordCount.put(tokens[i], wordCount.get(tokens[i]).intValue()+1);
else
wordCount.put(tokens[i], 1);
}
}
// Go to the next line
line=reader.readLine();
}
以下行有问题
if(!(tokens[i+1].isEmpty()))
和 if(!(tokens[i+2].isEmpty()))
实际上它说:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
发生这种情况是因为文件中的最后一个单词后面没有两个单词吗?如果我的猜测是正确的,我该如何纠正它,以便我可以停在文件的最后一个字处。如果我的猜测是错误的,请告诉我原因。 注意:这只是显示我的问题的示例
最佳答案
Does that happen because of the last word in the file where there are no two words after.
是的,这是正确的。
If my guess is right , how can I correct that so I can stop in the last word of the file.
首先检查是否超过了数组的长度:
if ((i + 1) < tokens.length && !(tokens[i+1].isEmpty()))
关于java - 读取每个单词和后面的两个单词并检查java中的一些条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12874229/