Reputation: 49
I am working on a java program to print a paragraph neatly. However, as it is now, the program prints the output on console like so:
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("|");
}
}
Now, I want to change it a little bit and print the output to another file (output.txt), but I am not that familiar Java so I need help with this. So what I don't know how to do is store the result in a String and format it the way printf does.
Upvotes: 0
Views: 603
Reputation: 324
You can use String.format() to do String formatting
So for instance this line:
System.out.printf("%s", words[index]);
Can be done like this:
String newStr = String.format("%s", words[index]);
And then you can append the rest of your lines to newStr. If you want to write the newString to a file use BufferedWriter.
Also your code call throws a Stackoverflow exception here
printSolution(words, print, print[n] - 1, width);
Upvotes: 1