我正在开发一个java程序来整齐地打印一个段落。但是,就像现在一样,程序在控制台上打印输出,如下所示:
private static void printSolution(String[] words, int[] print, int n,int width) {
if (n >= 0) {
printSolution(words, print, print[n] - 1, width);
int index = print[n];
System.out.printf("%s", words[index]);
width -= words[index].length();
++index;
for (; index <= n; index++) {
System.out.printf(" %s", words[index]);
width -= words[index].length() + 1;
}
while (width > 0) {
System.out.print(" ");
width--;
}
System.out.println("|");
}
}
现在,我想稍微更改它并将输出打印到另一个文件(output.txt),但我不熟悉Java,所以我需要帮助。所以我不知道怎么做的是将结果存储在String中,并按照printf的方式对其进行格式化。
答案 0 :(得分:1)
您可以使用String.format()进行字符串格式化
例如,这一行:
System.out.printf("%s", words[index]);
可以这样做:
String newStr = String.format("%s", words[index]);
然后你可以将其余的行追加到newStr。如果要将newString写入文件,请使用BufferedWriter。
此外,您的代码调用会抛出Stackoverflow异常
printSolution(words, print, print[n] - 1, width);