Search code examples
javaloopsfilewriter

Saving a variable's contents to a text file every time its value changes


My issue is that I would like to display the entire result of my calculations in the text file

aaa,
aab,
aba,
abb,
baa,
bab,
bba,
bbb

not just the last calculation bbb. I am thinking that this can be accomplished by writing a for loop that will print each combination? How would I do that?

Here is my code:

package test;

import java.io.FileWriter;
import java.io.IOException;

public class VarWriterTest{ 
String newline = System.getProperty("line.separator");

    public static void main(String[] args) {
        VarWriterTest VWT = new VarWriterTest();
        char[] alphalist = new char[] {'a', 'b'}; 
        StringExcersise.possibleStrings(3, alphalist,"");
    }
} 
class StringExcersise {

    public static void possibleStrings(int maxLength, char[] alphabet, String curr) {

        if(curr.length() == maxLength) {
            try(FileWriter out = new FileWriter("E:\\combo.txt");) {
                   out.write(curr.toCharArray());


            }catch(IOException ioe){
                System.out.println("Could not write file. Sorry.");
            }

         }else{
            for(int i = 0; i < alphabet.length; i++) {
                String oldCurr = curr;
                curr += alphabet[i];
                possibleStrings(maxLength,alphabet,curr);
                curr = oldCurr;
            }
        }
    }
}

Very Important! Please Read

If you choose to mark this question as a duplicate, please do not just refer me to the question. Please find an answer that appropriately answers a scenario close to this question. Believe it or not, not all questions marked as duplicates are actually duplicates.


Solution

  • Why don't you just write it to the file whenever you change it? Just move the writing logic from your base case to your else block. Of course, if you do that, you might want to pass in the FileWriter as a parameter, instead of opening and closing it every iteration.