【发布时间】: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