java - 是否可以设置程序输出中每行的最大字符数

标签 java format output

我正在尝试编写一个可以输出一篇文章的程序。我只是起诉 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 中输入一样。

提前致谢!

最佳答案

不,没有办法告诉 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 

关于java - 是否可以设置程序输出中每行的最大字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27206306/

相关文章:

java - 忽略布局边框

Java 使用 gsm 调制解调器发送短信时出错

java - 如何获得 XmlAdapter 的所有者 JAXBContext?

Mysql:创建表时将DATETIME的格式设置为 'DD-MM-YYYY HH:MM:SS'

sql - T-SQL 格式秒为 HH :MM:SS time

java - 将自定义二维数组打印为矩阵

java - 我可以从局部变量名称数组动态获取局部变量的值吗

java - 将日期 2/24 格式化为 "February, 24"

php - 如何在从 php 回显页面接收到的 .post() 输出数据中运行 javascript 函数

android - 在哪里写入文本文件以及如何为 SD 卡设置它