【问题标题】:problem is that the code print the letters twice问题是代码打印了两次字母
【发布时间】:2022-01-24 18:42:31
【问题描述】:

我正在编写一个从文件中读取的代码,然后打印每个字母的频率

这是我的代码

    BufferedReader read = new BufferedReader(new FileReader("Text.txt"));
    BufferedWriter write = new BufferedWriter(new FileWriter("Output.text"));

     String str = "";
     str = read.readLine();
     str = str.toUpperCase();
    
    while ((str = read.readLine()) != null) {
        int[] count = new int[26];
        str = str.toUpperCase();
         
        for (int i = 0 ; i < str.length(); i++) {
            if (str.charAt(i) >= 'A'  && str.charAt(i) <= 'Z') {
                count[str.charAt(i) - 'A']++;
            }
        }

        for (int i = 0; i < count.length; i++) {
            if (count[i] >= 0) {
                write.write("The frequency of letter " + (char) ('a' + i) + " = " + count[i]);
                write.newLine();
            }
        }
        
    }

但问题是代码会打印两次字母,即使我将字母转换为大写。 我该如何解决这个问题?

非常感谢你们

【问题讨论】:

  • 你能显示你的输出文件吗?您是否尝试过在代码中设置断点?此外,您需要关闭输出编写器。
  • 首先定位 where 打印两次。减少该打印语句,直到它打印错误的内容。涉及哪些变量?然后追溯:哪些代码行处理这些变量?他们在做什么?另外,请注意,您读取的第一个字符串被丢弃:您声明str,将一行文本读入其中,将其设为大写,然后由于while ((str = read.readLine()) != null) 而立即覆盖它。

标签: java string file for-loop


【解决方案1】:

如果您的输入文件有两行,则频率将被打印“两次”,因为您的文件编写器位于 for-each-line 循环内。

如果您尝试打印整个文件的字符频率,那么试试这个

try (BufferedReader read = new BufferedReader(new FileReader("Text.txt"));
    BufferedWriter write = new BufferedWriter(new FileWriter("Output.text"))) {
    // counts for file
    int[] count = new int[26];

    // read whole file
    String str;
    while ((str = read.readLine()) != null) {
        str = str.toUpperCase();
        for (int i = 0 ; i < str.length(); i++) {
            if (str.charAt(i) >= 'A'  && str.charAt(i) <= 'Z') {
                count[str.charAt(i) - 'A']++;
            }
        }
    }
    // loop counts and write frequencies to output file
    for (int i = 0; i < count.length; i++) {
        if (count[i] >= 0) {
            write.write("The frequency of letter " + (char) ('a' + i) + " = " + count[i]);
            write.newLine();
        }
    }
} catch (Exception e) {
    e.printStackTrace();
} 

对于大文件,您可能需要long[] count

【讨论】:

  • 效果很好,你解决了我的问题。谢谢。
猜你喜欢
  • 2021-05-28
  • 2012-05-05
  • 1970-01-01
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 2012-03-23
相关资源
最近更新 更多