2016-12-16 5 views
1

私はオブジェクトとクラスを学ぼうとしています。ここに私の問題があります:ファイルの各行は、1つのゲームの結果を保持します:2チームの名前とスコア。私は次のようなメモ帳を使ってファイルを作成しました:JavaのStringクラスとFileクラスを使用してファイルから名前の数を数えるには?

Panthers 5 Tigers 5 

Sky  2 Panthers 5 

Tigers 1 Sky  0 

Sky  2 Panthers 1 

Tigers 1 Sky  4 

私はファイルに読み込み、ファイル内のチームの数を数えようとしました。たとえば、このファイルには3つの異なるチームがあります。 "パンサー、タイガース、スカイ"。しかし、プログラムがなければ、コンピュータはどのくらいのチームを知っていない。

私はサッカーのクラス

private n; 
private String[] team; 

私はここにある

File inputFile = new File(filename); 
Scanner inFile = new Scanner(inputFile); 
n = 1; 

team = new String[n]; // Create a String array of n 

team[n-1] = inFile.next(); 

while(inFile.hasNext()){ 

    String num = inFile.nextInt(); //For the scores next to team's name 

    String name = inFile.next(); // Read another name and store it to String name 

    while(checkDuplicate(name)) // Check if name and team[i=0 to n] are the same return true 
    { 
     num = inFile.nextInt(); 
     name = inFile.next(); 
    } 

    n = n + 1; // Increase string array size to 1 
    team = new String[n]; 
    team[n - 1] = name; 

} 

    System.out.print("Number of teams: " + n); 

    System.out.print("Name of the teams: "); 
    for(int i = 0; i < n; i++) 
     System.out.print(team[i] + " "); 

ダウンファイルを読むためにサッカーのクラスのサッカー(文字列のファイル名)コンストラクタでファイルやスキャナを使用中に文字列配列を作成しました私のcheckDuplicate()ヘルパーメソッド

private boolean checkDuplicate(String name) 
{ 
    int count = 0; 
    for(int i = 0; i < n; i++) 
    { 
     if(name.equals(team[i])) 
      count = count + 1; 
    } 

    if(count > 1) 
     return true; 
    return false; 
} 
+0

ありがとうございます。ロシア語Osmanov –

+0

あなたの質問は正確ですか?もっと具体的にしてください –

+0

私はJavaを使って "scores.txt"のようなファイルを読んでいます。ファイルを調べてサッカーチームの名前を見ることができるプログラムを書いています。この名前をString配列のex:String [] teamに格納し、その数を1に増やします。これは、team [n]文字列配列の名前と同じ名前が表示された場合、名前を文字列配列または増加カウント(カウントは同じままです)。結局、カウントはチームの数です。 –

答えて

0

これは改善が必要ですが、それを使用することができます:

Map<String, Long> map = Files.lines(Paths.get("score.txt")) 
      .flatMap(line -> Stream.of(line.split("\\d+"))) 
      .map(team -> team.trim()) 
      .filter(team -> !team.isEmpty()) 
      .collect(Collectors.groupingBy(c -> c, Collectors.counting())); 
map.entrySet().forEach(e -> System.out.println(e.getKey() + " " + e.getValue())); 

チーム名とその繰り返し番号が表示されます。

Sky 4 
Panthers 3 
Tigers 3 
関連する問題