【问题标题】:Please help me read a file and count how many specific letter in it JAVA请帮我阅读一个文件并计算其中有多少特定字母 JAVA
【发布时间】:2015-11-18 06:42:20
【问题描述】:

这是我目前的方法。我试图在一个名为 in.txt 的文件中计算一个 A 字母。

public void countFile() {

  BufferedReader reader;
  int counter=0;

  try {
    reader = new BufferedReader(new FileReader("in.txt"));
  } 
  catch(IOException ioException) {
    System.err.println("Error Opening File: Terminating");
    System.exit(1);
  }
  int data = reader.read();  
  while(data != -1) {
    char charToSearch = 'A';

    //this is the part i mess up and i dont know how to fix it the char data have to be int and the char to search is char.

    if(charToSearch = (char) data); {
      counter++;
    }
  };
  reader.close();

  System.out.println(counter);
}

感谢大家帮助我。我一直在努力,但我无法解决它。

【问题讨论】:

  • (1) 比较两个值是否相等的 Java 运算符是什么? (2) if 语句的正确语法是什么?
  • ===while() {...}; 之间有区别是错误的
  • (3) 你有一个循环,直到data-1。但是,data 在您的循环中的哪个位置发生了变化?
  • 谢谢大家。你们是我所拥有的最好的社区。​​span>

标签: java file character


【解决方案1】:

除了@ajb 和@thegauravmahawar 提到的if 问题,我们还需要正确处理异常。此外,我们需要处理 while 循环以正确地从 BufferedReader 读取,正如@ajb 所建议的那样。代码如下:

public void countFile() {
    BufferedReader reader;
    int counter = 0;
    try {
        reader = new BufferedReader(new FileReader("in.txt"));
        int data;
        while ((data = reader.read()) != -1) {
            char charToSearch = 'A';
            if (charToSearch == (char) data) {
                counter++;
            }
        }
        reader.close();
        System.out.println(counter);
    } catch (IOException ioException) {
        System.err.println("Error Opening File: Terminating");
        System.exit(1);
    }
}

【讨论】:

  • @LeoKao 非常感谢!也感谢所有评论者的提示!
猜你喜欢
  • 1970-01-01
  • 2015-10-10
  • 2019-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
相关资源
最近更新 更多