-4

So I have received quite a few tips and acquired some resources for learning Java since joining this community. I have now reached week 6 in my class and am working through my third project. I feel like I'm learning a lot but I also have a long road ahead if I want to master Java.

My question this time is how do I get my code to save more than one output to file?

Part of my current project is to do the following:

"When the window is closed, the efficiency values should be computed with >values of n from 0 to 10 and written to a file. Each line of the file > >should contain the value of n, the efficiency of the iterative method for >that value of n and the efficiency of the recursive method. The values >should be separated by commas so the file can be opened with Excel."

I have managed to get the program to write a single entry into the output file. However,I either made an error in the code or missing something critical. Can someone point me to the correct solution? I think I may have to create an array, store the outputs there, then output the array to csv. I have looked at roseindia and viralpatel but those didn't reveal what I was hoping.

Sequence (part I'm screwing up)

package cmisproject3;

public class Sequence {

    private static int efficiency = 0;

    // method to compute iterative
    public static int computeIterative(int n) {
        int result = 0;
        efficiency = 0;
        if (n == 0) {
            result = 0;
        } else if (n == 1) {
            result = 1;
        } else {
            int secondPrevious = 0;
            int previous = 1;
            for (int i = 2; i <= n; i++) {
                efficiency++;
                result = 2 * previous + secondPrevious;
                secondPrevious = previous;
                previous = result;
            }
        }
        return result;
    }

    // method to comopute recursive
    public static int computeRecursive(int n) {
        efficiency = 0;
        return computeRecursiveHelper(n);
    }

    private static int computeRecursiveHelper(int n) {
        if (n == 0) {
            return 0;
        } else if (n == 1) {
            efficiency++;
            return 1;
        } else {
            efficiency++;
            return 2 * computeIterative(n - 1) + computeIterative(n - 2);
        }
    }

    public static int getEfficiency() {
        return efficiency;
    }
}

GUI (nailed it?)

package cmisproject3;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.*;

public class CMISProject3 extends JFrame implements ActionListener {

    private final int           TWICE           = 2;
    private JLabel              jLabel1         = new JLabel(), jLabel2 = new JLabel(), jLabel3 = new JLabel(), jLabel4 = new JLabel(), jLabel5 = new JLabel(), jLabel6 = new JLabel();
    private ButtonGroup         radioButtons    = new ButtonGroup();
    private JRadioButton        iterativeBtn    = new JRadioButton(), recursiveBtn = new JRadioButton();
    private JTextField          enterN          = new JTextField(16), textResult = new JTextField(16), textEfficiency = new JTextField(16);
    private JButton             computeBtn      = new JButton();
    private int                 efficiency;
    private Sequence            sequence;
    private static FileWriter   fileWriter;
    private File                file            = new File("output.txt");

    // Beginning of the constructor for the GUI
    public CMISProject3() throws IOException {

        sequence = new Sequence();
        setSize(300, 200); // define size of GUI
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        getContentPane().setLayout(new GridLayout(6, 2));
        getContentPane().add(jLabel4);
        radioButtons.add(iterativeBtn);
        iterativeBtn.setSelected(true); // sets Iterative as default GUI selection
        iterativeBtn.setText("Iterative");
        getContentPane().add(iterativeBtn);
        getContentPane().add(jLabel5);
        radioButtons.add(recursiveBtn);
        recursiveBtn.setText("Recursive");
        getContentPane().add(recursiveBtn);
        jLabel1.setText("Enter n: ");
        getContentPane().add(jLabel1);
        getContentPane().add(enterN);
        getContentPane().add(jLabel6);
        computeBtn.setText("Compute");
        computeBtn.addActionListener(this);
        getContentPane().add(computeBtn);

        jLabel2.setText("Result: ");
        getContentPane().add(jLabel2);
        getContentPane().add(textResult);
        textResult.setEditable(false);
        jLabel3.setText("Efficiency: ");
        getContentPane().add(jLabel3);
        getContentPane().add(textEfficiency);
        textEfficiency.setEditable(false);
        pack();
    }

    public void actionPerformed(ActionEvent event) {
        int result;
        efficiency = 0;
        try {
            fileWriter = new FileWriter(file);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (iterativeBtn.isSelected()) {
            result = sequence.computeIterative(Integer.parseInt(enterN.getText()));
        } else {
            result = sequence.computeRecursive(Integer.parseInt(enterN.getText()));
        }
        try {
            System.out.println(result);
            fileWriter.write(result + ", " + sequence.getEfficiency());
        } catch (IOException e) {
            e.printStackTrace();
        }
        textResult.setText(Integer.toString(result));
        textEfficiency.setText(Integer.toString(sequence.getEfficiency()));
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        CMISProject3 CMISProject3 = new CMISProject3();
        CMISProject3.setVisible(true);
    }
}

For those interested, here are the parameters I'm working within. Instructions

Feralix
  • 3
  • 1
  • 3

2 Answers2

0

You are reopening the file each time an action was performed without telling FileWriter to append instead of overwrite.

See: https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean)

KC Wong
  • 2,410
  • 1
  • 18
  • 26
0

I think you have a good start on your project. However, I see other problems apart from your question.

First I'll address your question then move on to other items. I assume when you say:

write a single entry into the output file

that you're saying you are able to write a single line to the file. So that would mean your question is: How can I write multiple lines to a file?

In that case you have at least two options. One is to setup your FileWriter to append rather than the default behavior of overwriting the existing file content.

Another option would be to avoid closing the FileWriter until you're finished writing. You could, for example, do this by moving the construction of your fileWriter to the constructor of your GUI and moving the call to the close method into an event handler that fires when the GUI closes.

Whatever you chose to do, you need to remember to write the newline character at the end of each line or else your file will be one very long line. So, modifying what you have now it would look like this:

fileWriter.write(result + ", " + sequence.getEfficiency()+"\n");

Other Issues:

Your Sequence.computeRecursiveHelper method is not recursive. A recursive method calls itself, yours does not do this.

I don't think you're following the instructions correctly. Perhaps you're just not finished yet and you intend to modify your code. If that is the case you can ignore what I'm about to point out. The instructions state:

When the window is closed, the efficiency values should be computed with values of n from 0 to 10 and written to a file.

You are currently writing to the file every time the user clicks the "Compute" button rather than doing the above. Also, you're not writing the correct data - you're writing the value you got based on the user's input not values obtained using n from 0 to 10.

D.B.
  • 4,523
  • 2
  • 19
  • 39