BufferedWriter不逐行写入数据

发布于 2025-01-11 09:15:27 字数 11232 浏览 0 评论 0原文

目前正在尝试从显示基准测试结果的 System.out.println() 语句中编辑我的旧代码,以将结果写入 2 个不同的 .txt 文件。我这样做是为了创建一个新程序,该程序使用 JFileChooser 选择 2 个 .txt 文件之一并在 JTable 上显示数据。问题是 BufferedWriter 仅将最后一组数据值写入 10 倍,因此我无法在 JTable 中显示正确的结果。

BenchmarkSorts.java:

/**
 * 
 * BenchmarkSorts is going to generate arrays consisting of random integers the size of which is supplied from SortMain.java.
 * It will then send the randomly generated array to be sorted using the Quick Sort Algorithm both Iteratively and Recursively
 * a total of 50 times each and display the benchmark results to the user.
 */

//=========
//packages
//=========
import java.io.*;
import java.util.Random;

//==============================
//start of class BenchmarkSorts
//==============================
public class BenchmarkSorts {

    //==========
    //variables
    //==========
    private int[] unsortedArray;
    private int iterativeCount = 0;
    private int recursiveCount = 0;
    private long iterativeTime, recursiveTime;
    private int[] iterativeCountLog = new int[50];
    private int[] recursiveCountLog = new int[50];
    private int iCounter = 0;
    private int rCounter = 0;
    private long[] iterativeTimeLog = new long[50];
    private long[] recursiveTimeLog = new long[50];
    private int arraySize;
    
    private FileWriter iFileWriter = new FileWriter("iterativeResults.txt");
    private FileWriter rFileWriter = new FileWriter("recursiveResults.txt");
    
    private BufferedWriter iBuffer = new BufferedWriter(iFileWriter);
    private BufferedWriter rBuffer = new BufferedWriter(rFileWriter);

    //=========
    //invoking
    //=========
    private QuickSort quickSort = new QuickSort();

    //============
    //constructor
    //============
    public BenchmarkSorts(int[] sizes) throws Exception {

        //==========================================================
        //for loop to add the sizes of the arrays to be benchmarked
        //==========================================================
        for(int i = 0; i < sizes.length; i++){
            arraySize = sizes[i];
            @SuppressWarnings("unused")
            BenchmarkSorts bms = new BenchmarkSorts(arraySize);        
        }
    }

    //========================================================
    //method to add random numbers to the array index size,
    //then send them to be sorted iteratively and recursively
    //before being displayed with the benchmark results
    //========================================================
    private BenchmarkSorts(int n) throws Exception {

        //=================================
        //nested for loops to run 50 times
        //creating arrays
        //=================================
        for(int i = 0; i < 50; i++) {
            unsortedArray = new int[n];

            for(int j = 0; j < n; j++) {
                Random randNum = new Random();
                unsortedArray[j] = (randNum.nextInt(1000));
            }
            runSorts();
        }
        displayReport(n);
    }

    //=========================================================
    //method to sort unsortedArray iteratively and recursively
    //while keeping track of count, time(in nano seconds)
    //=========================================================
    public void runSorts() throws Exception {

        //=========================================
        //creating 2 temporary arrays to be sorted
        //=========================================
        int[] tempArray1 = unsortedArray;
        int[] tempArray2 = unsortedArray;

        //============================
        //iterative sort and trackers
        //============================
        quickSort.iterativeSort(tempArray1);
        int returnCount = quickSort.getCount();
        long returnTime = quickSort.getTime();
        iterativeCount = iterativeCount + returnCount;
        iterativeTime = iterativeTime + returnTime;
        iterativeCountLog[iCounter] = returnCount;
        iterativeTimeLog[iCounter] = returnTime;
        iCounter++;

        //============================
        //recursive sort and trackers
        //============================
        quickSort.recursiveSort(tempArray2);
        returnCount = quickSort.getCount();
        returnTime = quickSort.getTime();
        recursiveCount = recursiveCount + returnCount;
        recursiveTime = recursiveTime + returnTime;
        recursiveCountLog[rCounter] = recursiveCount;
        recursiveTimeLog[rCounter] = recursiveTime;
        rCounter++;
    }

    //===================================================
    //method to display averages and standard deviations
    //===================================================
    public void displayReport(int arraySize) throws IOException {   

        //==========
        //variables
        //==========
        double iterativeAverageCount = 0;
        double iterativeAverageTime = 0;
        double recursiveAverageCount = 0;
        double recursiveAverageTime = 0;
        double iterativeSDCount = 0;
        double iterativeSDTime = 0;
        double recursiveSDCount = 0;
        double recursiveSDTime = 0;

        //========================================================
        //averaging the trackers for both iterative and recursive
        //========================================================
        iterativeAverageCount = iterativeCount / 50;
        iterativeAverageTime = iterativeTime / 50;
        recursiveAverageCount = recursiveCount / 50;
        recursiveAverageTime = recursiveTime / 50;

        //==========================================
        //for loop to calculate standard deviations
        //==========================================
        for(int i = 0; i < 50; i++) {
            iterativeSDCount = iterativeSDCount + Math.pow((iterativeCountLog[i] - iterativeAverageCount), 2);
            iterativeSDTime = iterativeSDTime + Math.pow((iterativeTimeLog[i] - iterativeAverageTime), 2);
            recursiveSDCount = recursiveSDCount + Math.pow((recursiveCountLog[i] - recursiveAverageCount), 2);
            recursiveSDTime = recursiveSDTime + Math.pow((recursiveTimeLog[i] - recursiveAverageTime), 2);
        }

        //====================
        //standard deviations
        //====================
        iterativeSDCount = Math.pow(iterativeSDCount, .5) / arraySize;
        iterativeSDTime = Math.pow(iterativeSDTime, .5) / arraySize;
        recursiveSDCount = Math.pow(recursiveSDCount, .5) / arraySize;
        recursiveSDTime = Math.pow(recursiveSDTime, .5) / arraySize;

        //====================================================
        //for loops to BufferedWrite data to respective files
        //====================================================
        for (int i = 0; i < 10; i++)    {
            iBuffer.write(arraySize + " " + iterativeAverageCount +  " " + iterativeSDCount + " " + iterativeAverageTime + " " + iterativeSDTime);
            iBuffer.newLine();
        }
        for (int i = 0; i < 10; i++)    {
            rBuffer.write(arraySize + " " + recursiveAverageCount +  " " + recursiveSDCount + " " + recursiveAverageTime + " " + recursiveSDTime);
            rBuffer.newLine();
        }
        iBuffer.close();
        rBuffer.close();
        
        //==========================================
        //old output that I want to write to a file
        //==========================================
        System.out.println("Iterative Quick Sort Results: " + "\nData Set Size (n): " + arraySize +
                ", Average Critical Operation Count: " + iterativeAverageCount + ", Standard Deviation of Count: " +
                iterativeSDCount + ", Average Execution Time: " + iterativeAverageTime + ", Standard Deviation of Time: " +
                iterativeSDTime);

        System.out.println("Recursive Quick Sort Results: " + "\nData Set Size (n): " + arraySize +
                ", Average Critical Operation Count: " + recursiveAverageCount + ", Standard Deviation of Count: " +
                recursiveSDCount + ", Average Execution Time: " + recursiveAverageTime + ", Standard Deviation of Time: " +
                recursiveSDTime);
    }
}

这是使用 System.out.println() 语句的旧输出:

Iterative Quick Sort Results: 
Data Set Size (n): 100, Average Critical Operation Count: 66.0, Standard Deviation of Count: 0.13490737563232041, Average Execution Time: 11528.0, Standard Deviation of Time: 394.80891580611495
Recursive Quick Sort Results: 
Data Set Size (n): 100, Average Critical Operation Count: 99.0, Standard Deviation of Count: 199.0490957025427, Average Execution Time: 36124.0, Standard Deviation of Time: 78349.10253729777
Iterative Quick Sort Results: 
Data Set Size (n): 200, Average Critical Operation Count: 133.0, Standard Deviation of Count: 0.11224972160321825, Average Execution Time: 27364.0, Standard Deviation of Time: 544.5295033329232
Recursive Quick Sort Results: 
Data Set Size (n): 200, Average Critical Operation Count: 199.0, Standard Deviation of Count: 200.05439416568686, Average Execution Time: 29262.0, Standard Deviation of Time: 27784.950723818103
...
...
Iterative Quick Sort Results: 
Data Set Size (n): 12000, Average Critical Operation Count: 11000.0, Standard Deviation of Count: 2.6352313834736497E-4, Average Execution Time: 720028.0, Standard Deviation of Time: 69.97877063001957
Recursive Quick Sort Results: 
Data Set Size (n): 12000, Average Critical Operation Count: 11999.0, Standard Deviation of Count: 201.04293765444527, Average Execution Time: 6.034408E7, Standard Deviation of Time: 1011471.3254720564

如您所见,它为 [100.. .12000](我剪掉了中间部分以缩短总长度)。

然而,生成的 2 个 .txt 文件仅显示最后一个 arraySize [12000] 10x,我不明白为什么

iterativeResult.txt:

12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957

recursiveResult.txt:

12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564

Currently trying to edit my old code from System.out.println() statements that display the results of a benchmark test to writing the results to 2 different .txt files. I am doing this so I can create a new program that uses JFileChooser to select one of the 2 .txt files and display the data on a JTable. The problem is the BufferedWriter is only writing the last set of data values 10x over so I cant display the correct results in my JTable.

BenchmarkSorts.java:

/**
 * 
 * BenchmarkSorts is going to generate arrays consisting of random integers the size of which is supplied from SortMain.java.
 * It will then send the randomly generated array to be sorted using the Quick Sort Algorithm both Iteratively and Recursively
 * a total of 50 times each and display the benchmark results to the user.
 */

//=========
//packages
//=========
import java.io.*;
import java.util.Random;

//==============================
//start of class BenchmarkSorts
//==============================
public class BenchmarkSorts {

    //==========
    //variables
    //==========
    private int[] unsortedArray;
    private int iterativeCount = 0;
    private int recursiveCount = 0;
    private long iterativeTime, recursiveTime;
    private int[] iterativeCountLog = new int[50];
    private int[] recursiveCountLog = new int[50];
    private int iCounter = 0;
    private int rCounter = 0;
    private long[] iterativeTimeLog = new long[50];
    private long[] recursiveTimeLog = new long[50];
    private int arraySize;
    
    private FileWriter iFileWriter = new FileWriter("iterativeResults.txt");
    private FileWriter rFileWriter = new FileWriter("recursiveResults.txt");
    
    private BufferedWriter iBuffer = new BufferedWriter(iFileWriter);
    private BufferedWriter rBuffer = new BufferedWriter(rFileWriter);

    //=========
    //invoking
    //=========
    private QuickSort quickSort = new QuickSort();

    //============
    //constructor
    //============
    public BenchmarkSorts(int[] sizes) throws Exception {

        //==========================================================
        //for loop to add the sizes of the arrays to be benchmarked
        //==========================================================
        for(int i = 0; i < sizes.length; i++){
            arraySize = sizes[i];
            @SuppressWarnings("unused")
            BenchmarkSorts bms = new BenchmarkSorts(arraySize);        
        }
    }

    //========================================================
    //method to add random numbers to the array index size,
    //then send them to be sorted iteratively and recursively
    //before being displayed with the benchmark results
    //========================================================
    private BenchmarkSorts(int n) throws Exception {

        //=================================
        //nested for loops to run 50 times
        //creating arrays
        //=================================
        for(int i = 0; i < 50; i++) {
            unsortedArray = new int[n];

            for(int j = 0; j < n; j++) {
                Random randNum = new Random();
                unsortedArray[j] = (randNum.nextInt(1000));
            }
            runSorts();
        }
        displayReport(n);
    }

    //=========================================================
    //method to sort unsortedArray iteratively and recursively
    //while keeping track of count, time(in nano seconds)
    //=========================================================
    public void runSorts() throws Exception {

        //=========================================
        //creating 2 temporary arrays to be sorted
        //=========================================
        int[] tempArray1 = unsortedArray;
        int[] tempArray2 = unsortedArray;

        //============================
        //iterative sort and trackers
        //============================
        quickSort.iterativeSort(tempArray1);
        int returnCount = quickSort.getCount();
        long returnTime = quickSort.getTime();
        iterativeCount = iterativeCount + returnCount;
        iterativeTime = iterativeTime + returnTime;
        iterativeCountLog[iCounter] = returnCount;
        iterativeTimeLog[iCounter] = returnTime;
        iCounter++;

        //============================
        //recursive sort and trackers
        //============================
        quickSort.recursiveSort(tempArray2);
        returnCount = quickSort.getCount();
        returnTime = quickSort.getTime();
        recursiveCount = recursiveCount + returnCount;
        recursiveTime = recursiveTime + returnTime;
        recursiveCountLog[rCounter] = recursiveCount;
        recursiveTimeLog[rCounter] = recursiveTime;
        rCounter++;
    }

    //===================================================
    //method to display averages and standard deviations
    //===================================================
    public void displayReport(int arraySize) throws IOException {   

        //==========
        //variables
        //==========
        double iterativeAverageCount = 0;
        double iterativeAverageTime = 0;
        double recursiveAverageCount = 0;
        double recursiveAverageTime = 0;
        double iterativeSDCount = 0;
        double iterativeSDTime = 0;
        double recursiveSDCount = 0;
        double recursiveSDTime = 0;

        //========================================================
        //averaging the trackers for both iterative and recursive
        //========================================================
        iterativeAverageCount = iterativeCount / 50;
        iterativeAverageTime = iterativeTime / 50;
        recursiveAverageCount = recursiveCount / 50;
        recursiveAverageTime = recursiveTime / 50;

        //==========================================
        //for loop to calculate standard deviations
        //==========================================
        for(int i = 0; i < 50; i++) {
            iterativeSDCount = iterativeSDCount + Math.pow((iterativeCountLog[i] - iterativeAverageCount), 2);
            iterativeSDTime = iterativeSDTime + Math.pow((iterativeTimeLog[i] - iterativeAverageTime), 2);
            recursiveSDCount = recursiveSDCount + Math.pow((recursiveCountLog[i] - recursiveAverageCount), 2);
            recursiveSDTime = recursiveSDTime + Math.pow((recursiveTimeLog[i] - recursiveAverageTime), 2);
        }

        //====================
        //standard deviations
        //====================
        iterativeSDCount = Math.pow(iterativeSDCount, .5) / arraySize;
        iterativeSDTime = Math.pow(iterativeSDTime, .5) / arraySize;
        recursiveSDCount = Math.pow(recursiveSDCount, .5) / arraySize;
        recursiveSDTime = Math.pow(recursiveSDTime, .5) / arraySize;

        //====================================================
        //for loops to BufferedWrite data to respective files
        //====================================================
        for (int i = 0; i < 10; i++)    {
            iBuffer.write(arraySize + " " + iterativeAverageCount +  " " + iterativeSDCount + " " + iterativeAverageTime + " " + iterativeSDTime);
            iBuffer.newLine();
        }
        for (int i = 0; i < 10; i++)    {
            rBuffer.write(arraySize + " " + recursiveAverageCount +  " " + recursiveSDCount + " " + recursiveAverageTime + " " + recursiveSDTime);
            rBuffer.newLine();
        }
        iBuffer.close();
        rBuffer.close();
        
        //==========================================
        //old output that I want to write to a file
        //==========================================
        System.out.println("Iterative Quick Sort Results: " + "\nData Set Size (n): " + arraySize +
                ", Average Critical Operation Count: " + iterativeAverageCount + ", Standard Deviation of Count: " +
                iterativeSDCount + ", Average Execution Time: " + iterativeAverageTime + ", Standard Deviation of Time: " +
                iterativeSDTime);

        System.out.println("Recursive Quick Sort Results: " + "\nData Set Size (n): " + arraySize +
                ", Average Critical Operation Count: " + recursiveAverageCount + ", Standard Deviation of Count: " +
                recursiveSDCount + ", Average Execution Time: " + recursiveAverageTime + ", Standard Deviation of Time: " +
                recursiveSDTime);
    }
}

This is the old output using System.out.println() statements:

Iterative Quick Sort Results: 
Data Set Size (n): 100, Average Critical Operation Count: 66.0, Standard Deviation of Count: 0.13490737563232041, Average Execution Time: 11528.0, Standard Deviation of Time: 394.80891580611495
Recursive Quick Sort Results: 
Data Set Size (n): 100, Average Critical Operation Count: 99.0, Standard Deviation of Count: 199.0490957025427, Average Execution Time: 36124.0, Standard Deviation of Time: 78349.10253729777
Iterative Quick Sort Results: 
Data Set Size (n): 200, Average Critical Operation Count: 133.0, Standard Deviation of Count: 0.11224972160321825, Average Execution Time: 27364.0, Standard Deviation of Time: 544.5295033329232
Recursive Quick Sort Results: 
Data Set Size (n): 200, Average Critical Operation Count: 199.0, Standard Deviation of Count: 200.05439416568686, Average Execution Time: 29262.0, Standard Deviation of Time: 27784.950723818103
...
...
Iterative Quick Sort Results: 
Data Set Size (n): 12000, Average Critical Operation Count: 11000.0, Standard Deviation of Count: 2.6352313834736497E-4, Average Execution Time: 720028.0, Standard Deviation of Time: 69.97877063001957
Recursive Quick Sort Results: 
Data Set Size (n): 12000, Average Critical Operation Count: 11999.0, Standard Deviation of Count: 201.04293765444527, Average Execution Time: 6.034408E7, Standard Deviation of Time: 1011471.3254720564

As you can see it produces the correct outputs for all arraySize's from [100...12000] (I cut out the mid section to shorten the total length).

The 2 .txt files produced however only display the last arraySize [12000] 10x and I can't figure out why

iterativeResult.txt:

12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957
12000 11000.0 2.6352313834736497E-4 720028.0 69.97877063001957

recursiveResult.txt:

12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564
12000 11999.0 201.04293765444527 6.034408E7 1011471.3254720564

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞎闹 2025-01-18 09:15:27

看起来普遍很混乱。

//========================================================
//method to add random numbers to the array index size,
//then send them to be sorted iteratively and recursively
//before being displayed with the benchmark results
//========================================================
private BenchmarkSorts(int n)  

这是一个构造函数,而不是方法,因此每次使用它都会构造(!)一个新的 BenchmarkSorts 实例,每个实例都有自己的一组实例变量。而且您显然知道它是一个构造函数,因为要使用它,您编写了 new BenchmarkSorts(...) - 这意味着使用第一个构造函数创建一个对象最终会使用第二个构造函数创建其中许多对象,这些实例都没有被真正使用。回想起来,通过抑制未使用变量警告来“修复”它可能不是一个好主意。

这可能是你的错误的根源。每个实例都会创建新的 BufferedWriter,每个实例都会覆盖同一个文件。

另外,

int[] tempArray1 = unsortedArray;
int[] tempArray2 = unsortedArray;

您仍然只有一个数组。

您的第一个修复应该是将第二个构造函数转换为方法。然后担心您是否真的想要 1 个数组的 2 个副本。

It looks generally confused.

//========================================================
//method to add random numbers to the array index size,
//then send them to be sorted iteratively and recursively
//before being displayed with the benchmark results
//========================================================
private BenchmarkSorts(int n)  

That's a constructor, not a method, so each use of it will construct (!) a new BenchmarkSorts instance, each of which has its own set of instance variables. And you apparently know it's a constructor, because to use it you wrote new BenchmarkSorts(...) - which means that creating one object using the first constructor ends up creating many of them using the second constructor, none of which instances are really used. Probably not a good idea in retrospect to have 'fixed' the unused-variable warning by suppressing it.

And this is probably the source of your bug. Each instance creates new BufferedWriters, each of which overwrites the same file.

Also,

int[] tempArray1 = unsortedArray;
int[] tempArray2 = unsortedArray;

You still have exactly one array.

Your first fix should be to turn the 2nd constructor into a method. Then worry about whether you really wanted 2 copies of 1 array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文