我正在尝试编写一个可以输出一篇文章的程序。我只是起诉System.out.print();在每个段落的开头用\ t和每个段落末尾的\ n的每个句子的函数。
所以它看起来像这样:
System.out.print("\tParagraph 1 Sentence 1");
System.out.print("Paragraph 1 Sentence 2");
System.out.print("Paragraph 1 Sentence 3");
System.out.print("Paragraph 1 Sentence 4\n");
System.out.print("\tParagraph 2 Sentence 2");
System.out.print("Paragraph 2 Sentence 2");
System.out.print("Paragraph 2 Sentence 3");
System.out.print("Paragraph 2 Sentence 4\n");
但是这会在一行上打印出每个段落。
我想知道是否可以设置每行打印的最大字符数,以便它自动返回,就好像我在Word中键入它一样。
提前致谢!
答案 0 :(得分:0)
不,没有办法告诉API在80个字符之后添加换行符等等。
您必须滚动自己的“段落打印机”,以跟踪自行开始以来已打印的字符数,然后输出换行符。
这可以让你了解我的意思:
String[] paragraphs = {
"Paragraph 1 Sentence 1. Paragraph 1 Sentence 2. Paragraph 1 Sentence 3. Paragraph 1 Sentence 4.",
"Paragraph 2 Sentence 1. Paragraph 2 Sentence 2. Paragraph 2 Sentence 3. Paragraph 2 Sentence 4"
};
for (String paragraph : paragraphs) {
Scanner s = new Scanner(paragraph);
System.out.print(" "); // instead of \t
int col = 8;
while (s.hasNext()) {
String word = s.next();
if (col + word.length() > 50) {
System.out.println();
col = 0;
}
System.out.print(word + " ");
col += word.length() + 1;
}
System.out.println();
}
<强>输出:强>
Paragraph 1 Sentence 1. Paragraph 1
Sentence 2. Paragraph 1 Sentence 3. Paragraph 1
Sentence 4.
Paragraph 2 Sentence 1. Paragraph 2
Sentence 2. Paragraph 2 Sentence 3. Paragraph 2
Sentence 4
答案 1 :(得分:0)
如果你想要类似于Word的东西,那么你可能想要使用的代码不仅仅是分割一行(包装,通常由文本编辑器调用)给定最大数量字符(可以使用String类中的一些方法轻松实现,例如 split ,可能还有 StringBuilder 。
就此而言,我建议您使用来自&#34; The Java Tutorials&#34; (来自Oracle):https://docs.oracle.com/javase/tutorial/i18n/text/line.html
如页面中所述,示例是与语言环境无关的代码,因此它应该足以满足您的需求。