0

好的,所以我有两个 .txt 文件,一个名为“input.txt”,另一个名为“output.txt”。要创建输出,我必须从输入中复制文本,但用 @'s 替换单词之间的所有空格,并在原始文本的每一行之后添加一个带有字符串“#NEW_LINE#”的新行

例如,如果 input.txt 是这样的:

the unstoppable marching of time
that is slowly guiding us all towards
an inevitable death 

那么 output.txt 应该是这样的:

the@unstoppable@marching@of@time
#NEW_LINE#
that@is@slowly@guiding@us@all@towards
#NEW_LINE#
an@inevitable@death 
#NEW_LINE#

无论如何,你明白了。

现在我对这个特定任务没有问题,但是我还被要求在屏幕上打印一条消息,显示两个文件中的文本总行数,另一个打印输出中@的总数。文本。虽然我在计算行数时没有问题,但它们的数字显示正确,但我确实很难弄清楚@的......我解释一下。

这是我最初尝试的代码的一部分:[顺便说一句,这整个事情发生在一个类上,当然,除了 main 之外没有其他方法。我认为这样会更简单 idk ‍♂️]

  File fsrc=new File("input.txt");         
  File fdes=new File("output.txt");        


  int atCount = 0; //number of @'s
  int lineCountIN=0; //number of input's lines
  int lineCountOUT=0; //number of output's lines

  FileReader fr = new FileReader(fsrc);           
  BufferedReader br =new BufferedReader(fr);

  FileWriter fw = new FileWriter(fdes);
  String s = null;

  while((s=br.readLine())!=null)            
  {
     if ((s.equals(" "))) {
     fw.write(s.replace(" ","@"));
     atCount++; } 
     else fw.write(s);
     fw.write("\n");
     lineCountOUT++;
     lineCountIN++;
     fw.write("#NEW_LINE#");
     fw.write("\n");
     lineCountOUT++;
     fw.flush();  
  }  
  fw.close();

[...]

System.out.println("Total instances of @ characters at output.txt: " + atCount);

屏幕上弹出的消息将始终是:“output.txt 中@ 字符的总数:0”。

后来我将 if-else 块更改为 do-while 块:

do {
         fw.write(s.replace(" ","@"));
         atCount++; } 
     while ((s.equals(" ")));

但随后消息并没有返回确切的@的数量,实际上它显示的数字恰好等于 lineCountIN 出于某种原因(例如,对于总共有 3 行的 input.txt 文件,最后的消息是:“output.txt 中 @ 字符的总实例数:3”)

所以是的,差不多就是这样,我猜我使用 atCount 的东西错了??任何帮助都将不胜感激<3

4

1 回答 1

0

您在这里找到空格的方法不正确是解决方案,而不是在整个字符串中搜索并计算每一行,您必须检查每个字符并计算它

    public static void main(String[] args) {

        String s  = "the unstoppable marching of time\n" +
                "that is slowly guiding us all towards\n" +
                "an inevitable death";
        int countSpace = 0;
        if (s.contains(" ")) {
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == ' ') {
                    countSpace++;
                }
            }
            s = s.replace(' ', '@');
        }
        System.out.println(s);
        System.out.println(countSpace);

    }
于 2020-04-28T17:21:09.013 回答