【问题标题】:How to write a program that processes text files and checks the end of a line?如何编写处理文本文件并检查行尾的程序?
【发布时间】:2017-07-24 01:11:12
【问题描述】:

我正在尝试编写一个程序,从输入文件中读取所有单词并将单词写入输出文件 sentence.txt。每当单词以句号、问号或感叹号结尾并且句号、问号或感叹号后跟引号时,它应该开始一个新行。否则,它用空格分隔单词。

到目前为止,我的代码一直在中间输出一长行,并且在标点符号后跟引号时不会打印新行。有人能指出我正确的方向吗?这是我目前所拥有的:

  Scanner console = new Scanner(System.in);
  System.out.print("Input file: ");
  String inputFileName = console.next();
  String outputFileName = "sentences.txt";

  File inputFile = new File(inputFileName);
  Scanner in = new Scanner(inputFile);
  PrintWriter out = new PrintWriter(outputFileName);


  while (in.hasNextLine())
  {  
     String line = in.nextLine();

     if (line.endsWith(".\"") || line.endsWith("!\"") || line.endsWith("?\"") ||
     line.endsWith(".") || line.endsWith("!") || line.endsWith("?"))
     {
        out.println(line);
     }

  }
  out.close();

【问题讨论】:

  • 提示:当line以标点符号或标点符号结尾时,你在做什么?
  • 你说得对,我应该为那个异常写一个 else 语句。但是我仍然在中间得到一长行代码,将几行连接为一条。似乎无法识别一行以其他标点符号结尾,但以句号结尾。

标签: java input output text-files


【解决方案1】:

您正在测试每一行输入以查看它是否应该结束一行输出,这对您没有多大帮助。 您需要测试输入的每个单词

这是一个简单的版本,它只读取标准输入并写入标准输出:

import java.util.Scanner;


public class Lines {

    public static void main(String[] args) {
        final Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
           final String word = in.next();
           if (shouldEndLine(word)) {
                System.out.println(word);
           } else {
                System.out.print(word);
                System.out.print(" ");
           }
        }
    }

    // I hid that big, ugly conditional inside a private method.
    private static boolean shouldEndLine(final String word) {
         return
           word.endsWith(".\"") ||
           word.endsWith("!\"") ||
           word.endsWith("?\"") ||
           word.endsWith(".") ||
           word.endsWith("!") ||
           word.endsWith("?");
    }

}

如果需要,您应该在退出前添加逻辑以打印最终换行符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2020-07-15
    相关资源
    最近更新 更多