我被要求编写一个程序,用于检查在我的计算机上创建的文本文件中是否存在团队名称,并且还说出它有多少次已被重复的文件?你能帮我解决吗?我写了代码来检查单词是否存在,但不知道如何检查它存在的次数。如何计算单词在文本文件中的次数
import java.util.*;
import java.io.*;
public class worldSeries
{
public boolean checkSeries() throws IOException
{
Scanner keyboard = new Scanner(System.in);
boolean result = false;
String[] winners = new String[200];
int i = 0 ;
File file = new File ("WorldSeriesWinners.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext() && i < winners.length)
{
winners[i] = inputFile.nextLine();
i++;
}
inputFile.close();
System.out.println(" Enter the Team's name you want to check : ");
String teamName = keyboard.nextLine();
for (int index = 0 ; index < winners.length ; index ++)
{
if (teamName.equals(winners[index]))
{
result = true;
}
}
return result;
}
public static void main(String[]Args)
{
worldSeries object1 = new worldSeries();
try
{
System.out.println(" The search result for the Team's name is : " + object1.checkSeries());
}
catch (IOException ioe)
{
System.out.println(" Exception!!! ");
ioe.printStackTrace();
}
}
}
只需创建一个计数器变量并增加它在你的for循环的,如果块。简单。 –