gpt4 book ai didi

Java在句子后添加换行符(为什么要双换行符来解决它)?

转载 作者:行者123 更新时间:2023-12-01 19:27:52 32 4
gpt4 key购买 nike

所以,当我尝试做一些关于 IOFile 的练习时,我遇到了一个关于在 txt 文件上写入字符串的问题,特别是在新文件中的每个句子后面写入一个新行(\n)。

这是我的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {

File Lyrics = new File("Lyrics.txt");
File output = new File ("output.txt");

try {
Scanner myReader = new Scanner (Lyrics);
try {
FileWriter FBI = new FileWriter(output);
while (myReader.hasNextLine()) {
FBI.write(myReader.nextLine());
FBI.write("\n");
}
FBI.close();
}catch (IOException e) {}
myReader.close();
}catch (FileNotFoundException e) {}
}
}

歌词.txt:

I could never find the right way to tell you
Have you noticed I've been gone
Cause I left behind the home that you made me
But I will carry it along

输出:

I could never find the right way to tell you
Have you noticed I've been gone
Cause I left behind the home that you made me
But I will carry it along
***invisible new line here

请求练习的输出:

I could never find the right way to tell you

Have you noticed I've been gone

Cause I left behind the home that you made me

But I will carry it along
***invisible new line here

在尝试添加新的代码行并尝试找出问题所在后,我只是修复了更改有关在

中添加新行的代码行
FBI.write("\n\n");

但我仍然很困惑为什么我必须添加一个双换行符(\n\n)来写句子,然后换行......

最佳答案

\n 表示换行。

如果我的文字是

FooBar\nHello World

我会收到

FooBar
Hello World

由于 \n (换行)使我们的 HelloWorld 移动到新行,所以一切都是正确的。但是您想要两行新行(当前一行 + 一个空白行)而不是一行,则必须使用 \n\n

输入

FooBar\n\nHello World

输出

FooBar

Hello World

关于Java在句子后添加换行符(为什么要双换行符来解决它)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60916633/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com