【问题标题】:How to read a text file into an array, count the number of occurrences and then display the count如何将文本文件读入数组,计算出现次数然后显示计数
【发布时间】:2018-11-05 02:27:27
【问题描述】:

文本文件包含随机符号,我想计算数字 0 - 9。

我正在努力弄清楚如何将文本文件读入数组,如何正确计算特定数字在数组中的出现次数,然后使用方法显示出现次数。

到目前为止,这是我的代码:

  // Get the filename.
  System.out.print("Enter the filename: ");
  String filename = keyboard.nextLine();

  // Open the file.
  File file = new File(filename);
  Scanner inputFile = new Scanner(file);

  char [] charMap = new char [1380];

  // Read lines from the file until no more are left.
  while (inputFile.hasNext())
  {
     // Read the map.
     String map = inputFile.nextLine();
     charMap = map.toCharArray();

     // Display the map.
     System.out.println(charMap);
  }

  // Close the file.
  inputFile.close();

} }

【问题讨论】:

    标签: java arrays methods


    【解决方案1】:

    根据您的示例,如果您想计算文件中每一行中的数字,这是一个工作示例。

    // Read lines from the file until no more are left.
            while (inputFile.hasNext())
            {
                // Read the map.
                String map = inputFile.nextLine();
                charMap = map.toCharArray();
    
                // Display the map.
                System.out.println(countNumber(charMap));
            }
    

    //方法

    private static int countNumber(char[] chars) {
            int count = 0;
            for (int i=0; i<chars.length; i++) {
                if (Character.isDigit(chars[i])) {
                    count++;
                }
            }
            return count;
        }
    

    或者,如果你可以用最简单的方式做到这一点,1) 将整个文件内容作为字符串读取,2) 从字符串构建数组,3) 从它们中计数,如下例所示:

    String inputFile = new Scanner(file).useDelimiter("\\z").next();
    
    char[] charMap = inputFile.toCharArray();
    System.out.println(countNumber(charMap));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多