简体   繁体   English

如何计算dat文件中的字符?

[英]How to count characters in a dat file?

Here is my code: 这是我的代码:

import java.util.Scanner;
import java.io.*;

public class BaseballStats
{

    public static void main (String[] args) throws IOException
    {
        Scanner fileScan, lineScan;
        String fileName;

        Scanner scan = new Scanner(System.in);

        System.out.print ("Enter the name of the input file: ");
        fileName = scan.nextLine();
        fileScan = new Scanner(new File(fileName));

        while (fileScan.hasNext())
        {
          fileName =fileScan.nextLine();
          System.out.println("Name: " + fileName);

          lineScan = new Scanner (fileName);
          lineScan.useDelimiter(",");
          while (lineScan.hasNext())
            System.out.println(" "+lineScan.next());

          System.out.println();
        }

    }
}

When you run the stats.dat file 当您运行stats.dat文件时

Willy Wonk,o,o,h,o,o,o,o,h,w,o,o,o,o,s,h,o,h
Shari Jones,h,o,o,s,s,h,o,o,o,h,o,o,o,o
Barry Bands,h,h,w,o,o,o,w,h,o,o,h,h,o,o,w,w,w,h,o,o
Sally Slugger,o,h,h,o,o,h,h,w
Missy Lots,o,o,s,o,o,w,o,o,o
Joe Jones,o,h,o,o,o,o,h,h,o,o,o,o,w,o,o,o,h,o,h,h
Larry Loop,w,s,o,o,o,h,o,o,h,s,o,o,o,h,h
Sarah Swift,o,o,o,o,h,h,w,o,o,o
Bill Bird,h,o,h,o,h,w,o,o,o,h,s,s,h,o,o,o,o,o,o
Don Daring,o,o,h,h,o,o,h,o,h,o,o,o,o,o,o,h
Jill Jet,o,s,s,h,o,o,h,h,o,o,o,h,o,h,w,o,o,h,h,o

I get this output: 我得到以下输出:

Name: Willy Wonk,o,o,h,o,o,o,o,h,w,o,o,o,o,s,h,o,h
 Willy Wonk
 o
 o
 h
 o
 o
 o
 o
 h
 w
 o
 o
 o
 o
 s
 h
 o
 h

Name: Shari Jones,h,o,o,s,s,h,o,o,o,h,o,o,o,o
 Shari Jones
 h
 o
 o
 s
 s
 h
 o
 o
 o
 h
 o
 o
 o
 o

Name: Barry Bands,h,h,w,o,o,o,w,h,o,o,h,h,o,o,w,w,w,h,o,o
 Barry Bands
 h
 h
 w
 o
 o
 o
 w
 h
 o
 o
 h
 h
 o
 o
 w
 w
 w
 h
 o
 o

Name: Sally Slugger,o,h,h,o,o,h,h,w
 Sally Slugger
 o
 h
 h
 o
 o
 h
 h
 w

Name: Missy Lots,o,o,s,o,o,w,o,o,o
 Missy Lots
 o
 o
 s
 o
 o
 w
 o
 o
 o

Name: Joe Jones,o,h,o,o,o,o,h,h,o,o,o,o,w,o,o,o,h,o,h,h
 Joe Jones
 o
 h
 o
 o
 o
 o
 h
 h
 o
 o
 o
 o
 w
 o
 o
 o
 h
 o
 h
 h

Name: Larry Loop,w,s,o,o,o,h,o,o,h,s,o,o,o,h,h
 Larry Loop
 w
 s
 o
 o
 o
 h
 o
 o
 h
 s
 o
 o
 o
 h
 h

Name: Sarah Swift,o,o,o,o,h,h,w,o,o,o
 Sarah Swift
 o
 o
 o
 o
 h
 h
 w
 o
 o
 o

Name: Bill Bird,h,o,h,o,h,w,o,o,o,h,s,s,h,o,o,o,o,o,o
 Bill Bird
 h
 o
 h
 o
 h
 w
 o
 o
 o
 h
 s
 s
 h
 o
 o
 o
 o
 o
 o

Name: Don Daring,o,o,h,h,o,o,h,o,h,o,o,o,o,o,o,h
 Don Daring
 o
 o
 h
 h
 o
 o
 h
 o
 h
 o
 o
 o
 o
 o
 o
 h

Name: Jill Jet,o,s,s,h,o,o,h,h,o,o,o,h,o,h,w,o,o,h,h,o
 Jill Jet
 o
 s
 s
 h
 o
 o
 h
 h
 o
 o
 o
 h
 o
 h
 w
 o
 o
 h
 h
 o

Question: Now I need to modify the inner loop that parses a line in the file so that instead of printing each part it counts (separately) the number of hits, outs, walks, and sacrifices. 问题:现在,我需要修改解析文件中一行的内部循环,以便与其打印每个部分(而不是打印每个部分),而是计入击打,出局,步行和牺牲的次数。 Each of these summary statistics should be printed for each player. 这些摘要统计信息中的每一个都应为每个玩家打印。

The problem I am having is that I do not know how to make it count specific characters and I do not know how to make it not count the characters in the name. 我遇到的问题是,我不知道如何使它计算特定字符,也不知道如何使它不计算名称中的字符。

If someone could guide me that would be great. 如果有人可以指导我,那就太好了。

You have just a few types of characters to count. 您只需要计算几种类型的字符。 You could simply use a separate counter for each: 您可以简单地为每个使用单独的计数器:

      int wCount = 0;
      int hCount = 0;
      // ...
      while (lineScan.hasNext()) {
        switch (lineScan.next()) {
            case 'w': wCount++; break;
            // ...
        }
      }
      // print the stats

Here is a full implementation of your main() method using the approach I would use myself given your input data. 这是main()方法的完整实现,使用的方法是根据给定您的输入数据使用我自己的方法。 First, I split each line of the stats.dat file on comma. 首先,我用逗号分割stats.dat文件的每一行。 This leaves us with an array, the first element of which is the player name, and the remaining elements which are individual game event statistics (eg out, walk). 这给我们留下了一个数组,其第一个元素是玩家名称,其余的元素是各个游戏事件的统计信息(例如,出门,走动)。 Next, I simply tally up the stats for each player and then display this to the console. 接下来,我简单地汇总每个玩家的统计信息,然后将其显示在控制台上。

public static void main (String[] args) throws IOException {
    Scanner fileScan;
    String fileName;

    Scanner scan = new Scanner(System.in);

    System.out.print ("Enter the name of the input file: ");
    fileName = scan.nextLine();
    fileScan = new Scanner(new File(fileName));

    while (fileScan.hasNext()) {
        String currLine = fileScan.nextLine();
        String[] parts = currLine.trim().split(",");

        String playerName = "";
        int hits=0, outs=0, walks=0, sacs=0;

        if (parts.length > 0) {
            playerName = parts[0];
        }

        for (int i=1; i < parts.length; ++i) {
            String stat = parts[i].trim();
            if (stat.equals("h")) {
                ++hits;
            }
            else if (stat.equals("o")) {
                ++outs;
            }
            else if (stat.equals("w")) {
                ++walks;
            }
            else if (stat.equals("s")) {
                ++sacs;
            }
        }

        // display aggregated player stats to the console
        System.out.println(playerName + ":");
        System.out.println("hits : "  + hits);
        System.out.println("outs : "  + outs);
        System.out.println("walks : " + walks);
        System.out.println("sacs : "  + sacs);
    }
}

Scanner is a heavyweight, so using it to simply read lines, and to split a line, is overkill. Scanner是重量级的,因此仅使用它来读取行并拆分行是过分的。 Use BufferedReader.readLine() and String.split() instead. 请改用BufferedReader.readLine()String.split() Also, don't pre-declare the variables, declare where initialized, whenever possible. 另外,不要预声明变量,要尽可能在初始化位置声明。

Calling split() will give you an array, where you know that first element is the name, so you skip it. 调用split()将为您提供一个数组,您知道第一个元素是名称,因此可以跳过它。

Scanner sysin = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
String fileName = sysin.nextLine();

try (BufferedReader fileIn = new BufferedReader(new FileReader(fileName))) {
    for (String line; (line = fileIn.readLine()) != null; ) {
        String[] values = line.split(",");
        int hits = 0, outs = 0, walks = 0, sacrifices = 0;
        for (int i = 1; i < values.length; i++)
            switch (values[i].charAt(0)) {
                case 'h': hits++;        break;
                case 'o': outs++;        break;
                case 'w': walks++;       break;
                case 's': sacrifices++;  break;
            }
        System.out.println(values[0] + ": " + hits + " hits, " +
                                              outs + " outs, " +
                                              walks + " walks, " +
                                              sacrifices + " sacrifices");
    }
}

For this I would simply use a Map to count the different types of data on each line. 为此,我只需要使用Map来计算每一行上不同类型的数据。 I'd split the data, the first item would always be the persons name and then tally up the count in the HashMap. 我将数据拆分,第一项始终是人员姓名,然后在HashMap中计算总数。 Adding different types of data is also easiest with this approach because all you need to do is add a type in the item lookup and you're done. 使用这种方法添加不同类型的数据也是最简单的,因为您要做的就是在项目查找中添加类型,然后就完成了。 An example is if you wanted to add ab for Bunt then you'd simply need to add 例如,如果您想为Bunt添加ab,则只需添加

itemLookup.put("b", "Bunt"); 

to the code and you'd be done. 代码,您将完成。 Here's the implementation. 这是实现。

I simply created a method that would process each line. 我只是创建了一个处理每一行的方法。 I'm assuming that the user can pass in the line from whatever feed they want. 我假设用户可以从他们想要的任何提要中传递代码。

import java.util.HashMap;
import java.util.Map;

public class CountCharacters {

    public static void main(String[] args) {
        CountCharacters.processLine("Willy Wonk,o,o,h,o,o,o,o,h,w,o,o,o,o,s,h,o,h");
    }

    static Map<String, String> itemLookup = new HashMap<>();

    static {
        itemLookup.put("s", "Strike");
        itemLookup.put("w", "Walk");
        itemLookup.put("o", "Out");
        itemLookup.put("h", "Hit");

    }

    public static void processLine(String currentLineReadFromFile) {
        String inputData[] = currentLineReadFromFile.split(",");
        HashMap<String, Integer> characterCount = new HashMap<>();

        for (String key : inputData) {
            Integer value = characterCount.get(key);
            if (value == null) {
                characterCount.put(key, 1);
            } else {
                value++;
                characterCount.put(key, value);
            }
        }

        // show counted characters of all items collected
        boolean firstItem = true;
        for (String character : characterCount.keySet()) {
            Integer value = characterCount.get(character);
            if (firstItem == true) {
                System.out.println(character);
                firstItem = false;
                continue;
            }
            System.out.println(itemLookup.get(character) + ":" + value);
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM