将arraylist结果添加到文本文件中

时间:2015-01-01 16:49:02

标签: java dynamic arraylist

在这个程序中,它将运行20次迭代。到达终端状态时,每次迭代都完成。我希望将所有20次迭代的结果写入文本文件,但目前只有最后一次迭代才会写入文本文件。

我想通过创建两个arraylists并添加变量" numsteps" (它包含迭代中的步骤数)和"奖励" (这相当于该迭代的总奖励)给两个arraylists'"""'并且""奖励"',它会自动将每次迭代的所有值插入到arraylists中,然后将arraylists输入到文本文件中。

但此刻它只会将numsteps的最后一次迭代和奖励插入到文本文件中。

有谁知道我哪里出错了?

            if (nextState.isTerminal()) {
         //storing total number of steps and total of rewards int x and y
        double reward = ((GridEnvir) env).total;
        int numsteps = (int) ((GridEnvir) env).numStepsInTrial;

        //create array for number of steps in trial  = steps
        ArrayList<Integer> steps = new ArrayList<Integer>();
        steps.add(numsteps);

        //create array for rewards in trial  = rewards
        ArrayList<Double> rewards = new ArrayList<Double>();
        rewards.add(reward);


        try {
          // method to write to a text file.   
          write(steps, rewards, 20);
        } catch (IOException e) {
            System.out.println("does work");
        }

        /// printing out to the console window each time the nextState.isTerminal() condition is reached
        System.out.println("\n Found goal in " + x + " steps "+ " total reward " + y);

        System.out.println(agt);
    }

}

下一个方法会将结果写入文本文件。

public static void write(ArrayList<Integer> numsteps, ArrayList<Double> reward,
        int episode) throws IOException {

    PrintWriter pw = new PrintWriter(
             // not actual (this part of code is hidden)
            "results.txt");


    int y[] = new int[episode];

    pw.write("NumSteps" + "\t " + "reward" + "\n");

    for (int i = 0; i < y.length; i++) {
        for (int a : numsteps) {
            for (Double b : reward)

                pw.write(a + "\t\t " + b + "\n");
        }// }

        pw.close();
    }

}}

1 个答案:

答案 0 :(得分:0)

您的代码如下:

for (int i = 0; i < y.length; i++) {
    for (int a : numsteps) {
        for (Double b : reward)
            pw.write(a + "\t\t " + b + "\n");
    }
    pw.close();
 }

因此,在第一次迭代中,它将写入文件numsteps和reward。但是一旦它被写入,当我为0时,你关闭流然后对于我作为1你尝试写入关闭流,这就是为什么你看到在文件中只写一次数据的原因。

尝试在for循环后删除pw.close(),将i作为变量来解决问题。