I have a loop enumeration all possible combinations of a sequence. I'm using a for loop and I get proper results in the console but but my outputted text file is inconsistent.
import java.io.*;
import java.io.PrintWriter;
public class WriteFile {
public static void main (String args[]) throws FileNotFoundException {
brute("12345", 5, new StringBuffer());
}
static void brute(String input, int depth, StringBuffer output) throws FileNotFoundException {
PrintWriter pw =
new PrintWriter("/Users/evanlivingston/test.txt");
if (depth == 0) {
System.out.println(output);
} else {
for (int i = 0; i < input.length(); i开发者_开发知识库++) {
pw.println(output);
output.append(input.charAt(i));
brute(input, depth - 1, output);
output.deleteCharAt(output.length() - 1);
}
pw.flush();
pw.close();
}
}
}
I'm not sure what's going wrong.
Each time you create a new PrintWriter, it starts writing to the file from beginning. Try writing to your file after you have constructed output
static void brute(String input, int depth, StringBuffer output) throws FileNotFoundException {
if (depth == 0) {
System.out.println(output);
PrintWriter pw =
new PrintWriter("/Users/evanlivingston/test.txt");
pw.println(output);
pw.flush();
pw.close();
} else {
for (int i = 0; i < input.length(); i++) {
output.append(input.charAt(i));
brute(input, depth - 1, output);
output.deleteCharAt(output.length() - 1);
}
}
}
精彩评论