我被要求编写一个程序来检查团队名称是否存在于我在计算机上创建的文本文件中,并且还说出在文件中重复了多少次?你能帮我吗?我已经编写了代码来检查该单词是否存在,但是不知道如何检查该单词存在的次数。
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();
}
}
}
取而代之的是,result = true;
您可以在循环内增加一个计数器。
例如:
int counter = 0;
for ( int index = 0 ; index < winners.length ; index ++ )
{
if ( teamName.equals(winners[index]))
{
counter = counter + 1;
}
}
然后,您可以将方法的返回类型更改为int
and return counter
。
仅返回true / false的方法可以使用新方法。如果返回值为0,则返回false,否则返回true。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句