[英]How to count the number of times a word is in the text file
我被要求編寫一個程序來檢查我在計算機上創建的文本文件中是否存在團隊名稱,並說明它在文件中重復了多少次? 你能幫我一下嗎? 我已經編寫了代碼來檢查這個詞是否存在,但不知道如何檢查它出現的次數。
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
循環
for(int index = 0 ; index < winners.length ; index++){
if ( teamName.equals(winners[index])){
result = true;
}
}
引入一個變量counter
,該counter
初始化為 0,如果團隊名稱匹配則遞增。
此外,我建議重新構建您的代碼。
String[]
存儲到String[] winners
。winners
是否包含團隊名稱。 這已經發生在您的方法checkSeries()
。 正如您可以從我之前的評論中想象的那樣,我會將 Scanner 代碼移動到 1 中描述的方法。請記住,方法名稱應該描述方法中發生的事情 - 因此checkSeries()
應該只檢查並返回是或否。checkSeries()
的 for 循環。 僅當checkSeries()
返回 true 時才需要調用此方法。而不是result = true;
你可以在循環內增加一個計數器。
例如:
int counter = 0;
for ( int index = 0 ; index < winners.length ; index ++ )
{
if ( teamName.equals(winners[index]))
{
counter = counter + 1;
}
}
然后您可以將方法的返回類型更改為int
並返回counter
。
只返回 true / false 的方法可以使用新方法。 如果返回值為 0,則返回 false,否則返回 true。
您可以使用以“key”作為單詞和“value”作為出現次數的 HashMap。 每當您閱讀一個單詞時,請檢查該單詞是否在地圖中可用並增加其值。 如果您需要代碼示例,請告訴我們。
如果我是你,我會在一個string
讀取一次輸入的所有文本,然后使用方法string.split(" ");
這將返回一個包含輸入中所有單詞的string
數組。 然后對 Array 執行循環並在輸入中計算您團隊的結果。
如果您在編寫代碼方面需要進一步幫助,請隨時詢問
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.