提问人:Eleonora Ferrari 提问时间:3/29/2020 最后编辑:Eleonora Ferrari 更新时间:3/29/2020 访问量:366
Java在句子后加换行(为什么要双换行来解决它)?
Java add new line after a sentence ( why double new line to solve it)?
问:
因此,当我尝试对 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) {}
}
}
Lyrics.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) 来写句子,然后是换行符......
答:
1赞
ᴇʟᴇvᴀтᴇ
3/29/2020
#1
换行符紧挨着上一行开始一个新行,没有间隙。如果你想在句子之间留一个空行,你需要添加一秒钟来创造一个间隙。\n
\n
2赞
jdickel
3/29/2020
#2
\n
表示换行符。
因此,如果我的文字是
FooBar\nHello World
我会收到
FooBar
Hello World
由于(换行)使我们搬到了新行,一切都是正确的。
但是你想要两个新行(当前一个+一个空行)而不是一个,你必须使用.\n
HelloWorld
\n\n
输入
FooBar\n\nHello World
输出
FooBar
Hello World
评论
FBI.write("ho");FBI.write("ho");
如果这是误解,将不带换行符。hoho