如何在一定行长后转到新行?

我有一个数组,它在达到某个字符限制后需要转到新行,但我不希望它截断数字。我尝试将数组转换为字符串以去除括号和空格,但我似乎无法将字符串转到正确位置的新行。我该如何实现?谢谢!


当前代码(这是一团糟,我尝试了其他帖子中的许多不同解决方案)


System.out.println(n + " (" + numDivisors + " proper divisors)");

    System.out.print("...proper divisors: ");


    String temp = Arrays.toString(properDivisors).replace("]", ",").replace(" ", "");

    String finalDiv = temp.substring(1, temp.length());

    if (finalDiv.length() > len) {

        for (int i = len; i <= len; i--){

            if (finalDiv.charAt(len) == ',') {

                finalDiv = finalDiv.replaceAll(".{" + i + "}", "$0\n\t\t    ");

                System.out.print(finalDiv);

            }

        }

    } else {

        System.out.println(finalDiv);

    }

期望输出


86268 (47 proper divisors)                                                               

...proper divisors: 1,2,3,4,6,7,12,13,14,21,26,28,39,42,52,78,79,84,91,

                    156,158,182,237,273,316,364,474,546,553,948,1027,

                    1092,1106,1659,2054,2212,3081,3318,4108,6162,6636,

                    7189,12324,14378,21567,28756,43134,


倚天杖
浏览 115回答 1
1回答

慕无忌1623718

如果你构建一个字符串会更容易,并且只有当你超过行长度时才打印它。不要 munge Arrays.toString(),只需自己构建字符串表示。String prefix = "...proper divisors: ";// Same number of chars as prefix, just all spaces.String emptyPrefix = prefix.replaceAll(".", " ");for (int i = 0; i < properDivisors.length;) {&nbsp; // Take as many of the items in the array as you can, without exceeding the&nbsp; // max line length.&nbsp; StringBuilder sb = new StringBuilder(prefix);&nbsp; for (; i < properDivisors.length; ++i) {&nbsp; &nbsp; int lengthBefore = sb.length();&nbsp; &nbsp; // Append the next item, and comma, if it would be needed.&nbsp; &nbsp; sb.append(properDivisors[i]);&nbsp; &nbsp; if (i + 1 < properDivisors.length) sb.append(",");&nbsp; &nbsp; if (sb.length() > maxWidth) {&nbsp; &nbsp; &nbsp; // Truncate back to the length before appending.&nbsp; &nbsp; &nbsp; sb.setLength(lengthBefore);&nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; }&nbsp; System.out.println(sb);&nbsp; // Blank out the prefix, so you will print leading spaces on next line.&nbsp; prefix = emptyPrefix;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java