【问题标题】:The number I'm trying to print out keeps getting add up in the next line我要打印的数字在下一行不断增加
【发布时间】:2020-07-02 10:56:04
【问题描述】:

我想从一个文本文档文件中读取几行,然后将每行的元音数写入另一个文本文档。

"vlez.txt" 是输入文件,"destinacija.txt" 是输出。

输入 -> 输出示例:

你好
世界
再见

在输出文件中,结果将是:

2(Hello 中的 2 个元音)
3(来自世界的 1 个元音 + 上一个)
7(你明白了..)

我的代码:

package prvaZad;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class prvaZadaca {

    public static void main(String[] args) throws IOException {

        BufferedReader in = new BufferedReader(new FileReader("vlez.txt"));
        PrintWriter out = new PrintWriter(new FileWriter("destinacija.txt"));
        StringBuilder sb = new StringBuilder();

        String line;
        int number = 0;
        while ((line = in.readLine()) != null) {

            sb.append(line);
            sb.append('\n');

            String lc = sb.toString().toLowerCase();
            for (int i=0; i<lc.length(); i++) {
                char ch = lc.charAt(i);

                if ("aeiouy".indexOf(ch) > -1) {
                    number++;
                }
            }
            out.print(number);
            out.print('\n');
            number = 0;
        }       

        if (in != null) 
            in.close();

        if (out != null)
            out.close();

        System.out.println(number);
    }
}

【问题讨论】:

  • 请将代码作为文本,而不是图像 :) 你也可以展示一个输入->输出的例子吗?
  • 太棒了。你能告诉我们你目前得到的输出吗?

标签: java file input output


【解决方案1】:

问题是你一直在StringBuilder后面添加行,换句话说,它会从0重新开始计数。

您可以通过在下一次迭代之前“清除”StringBuilder 来解决此问题:

out.print(number);
out.print("\n")
number = 0;
sb = new StringBuilder(); // a new empty StringBuilder

【讨论】:

    【解决方案2】:

    这段代码可以帮助你

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package javaapplication11;
    
    import java.util.Timer;
    
    /**
     *
     * @author Sem-6-INGENIERIAINDU
     */
    public class JavaApplication11 {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            String word = "Hello World Goodbye";
            String[] container = word.split(" ");
            for (String container1 : container) {
                System.err.println("The word:" + container1 + " has " + (container1.replaceAll("[^aeiou]", "")).length());
            }
        }
    
    }
    

    运行:单词:Hello 有 2 个单词:World 有 1 个单词:Goodbye 有 3 个 构建成功(总时间:0 秒)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2013-03-01
      相关资源
      最近更新 更多