【问题标题】:Save multiple outputs to csv file [duplicate]将多个输出保存到 csv 文件 [重复]
【发布时间】:2016-11-29 02:43:19
【问题描述】:

所以自从加入这个社区以来,我收到了很多学习 Java 的技巧和资源。现在我的班级已经到了第 6 周,并且正在完成我的第三个项目。我觉得我学到了很多东西,但如果我想掌握 Java,我还有很长的路要走。

这次我的问题是如何让我的代码将多个输出保存到文件中?

我当前项目的一部分是执行以下操作:

"当窗口关闭时,效率值应该用>从0到10的n值计算并写入文件。文件的每一行>应该包含n的值,迭代的效率“n 的值的方法和递归方法的效率。值应该用逗号分隔,以便可以用 Excel 打开文件。”

我已经设法让程序将单个条目写入输出文件。但是,我要么在代码中出错,要么遗漏了一些关键的东西。有人可以指出正确的解决方案吗?我想我可能必须创建一个数组,将输出存储在那里,然后将数组输出到 csv。我看过roseindia 和viralpatel,但这些并没有揭示我的希望。

序列(部分我搞砸了)

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(成功了吗?)

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);
    }
}

对于那些感兴趣的人,这里是我正在使用的参数。 Instructions

【问题讨论】:

  • 所有左对齐代码 == 很难阅读代码。您确定要让您的问题变得更难回答吗?

标签: java csv output


【解决方案1】:

每次执行操作时您都在重新打开文件,而没有告诉 FileWriter 追加而不是覆盖。

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

【讨论】:

    【解决方案2】:

    我认为您的项目有一个良好的开端。但是,除了您的问题之外,我还看到了其他问题。

    首先我会解决您的问题,然后再讨论其他项目。我假设当你说:

    将单个条目写入输出文件

    您是说您可以在文件中写入一行。所以这意味着您的问题是:如何将多行写入文件?

    在这种情况下,您至少有两个选择。一种是将您的FileWriter 设置为append,而不是覆盖现有文件内容的默认行为。

    另一种选择是避免关闭FileWriter,直到您完成写作。例如,您可以通过将 fileWriter 的构造移动到 GUI 的构造函数并将对 close 方法的调用移动到 GUI 关闭时触发的事件处理程序来执行此操作。

    无论您选择做什么,都需要记住在每一行的末尾写下换行符,否则您的文件将是一个很长的行。因此,修改您现在拥有的内容将如下所示:

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

    其他问题:

    您的Sequence.computeRecursiveHelper 方法不是递归的。递归方法调用自己,你的不会这样做。

    我认为您没有正确遵循说明。也许你还没有完成,你打算修改你的代码。如果是这种情况,您可以忽略我要指出的内容。指令状态:

    当窗口关闭时,效率值应该用 0 到 10 的 n 值计算并写入文件。

    您当前正在每次用户单击“计算”按钮而不是执行上述操作时写入文件。此外,您没有写入正确的数据 - 您正在写入基于用户输入获得的值,而不是使用从 0 到 10 的 n 获得的值。

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 2020-11-18
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 2019-07-02
      • 2020-09-19
      • 2022-11-25
      • 2021-07-14
      相关资源
      最近更新 更多