简体   繁体   English

将输入文件读入数组,对其进行排序,然后将其输出到文件中

[英]Reading input file into array, sorting it, then outputting it to a file

I'm very new to programming and java but I have an assignment where I'm have to create a program that opens and reads an input text file that has 12 integer numbers written in it, reads the numbers of the text file into an integer array that I create, passes the array as a parameter to a method that sorts the array from low to high, then writes these sorted array numbers to an output file. 我是编程和Java的新手,但我需要做一个作业,其中必须创建一个程序,该程序打开并读取输入了12个整数的输入文本文件,并将文本文件的编号读取为整数我创建的数组,将数组作为参数传递给将数组从低到高排序的方法,然后将这些排序后的数组编号写入输出文件。 The output file should also display the average of all the integers numbers, computed using a loop, and placed at the end of the sorted list of integers. 输出文件还应显示所有整数的平均值,这些平均值是使用循环计算的,并位于整数排序列表的末尾。

Below is what I have so far. 以下是到目前为止的内容。 I can't seem to figure out how to properly get the array sorted and sent back to the main function. 我似乎无法弄清楚如何正确地对数组进行排序并发送回主函数。 I'm also unclear how to get and output the average. 我也不清楚如何获得和输出平均值。 If anyone can help I'd greatly appreciate it. 如果有人可以提供帮助,我将不胜感激。 Thank you in advance. 先感谢您。

import java.util.Scanner;
import java.util.Arrays;

public class NumberSorter {

    public static void main(String[] args) throws Exception {    
        double sum = 0;    
        double avg = 0;
        double total = 0;
        int i = 0, 
        number = 0;
        int[] data_array = new int[12]; 
        java.io.File file = new java.io.File("numbers.txt"); 
        Scanner input = new Scanner(file);

        while(input.hasNext()){
           data_array[i] = input.nextInt();
           sortArray(data_array);
           avg = sum/total;
           java.io.PrintWriter output = new java.io.PrintWriter("dataout.txt");
           output.close();
        }
    }

    public static void sortArray(int[] data_array)
    {
        Arrays.sort(data_array);
    }
}

Your main problem with reading into your data_array is that you just read into position 0 each time as you never increment the value of i in your while loop. 读入data_array主要问题是每次您都读入位置0,因为您从不会在while循环中增加i的值。 So each time, you overwrite the first element of the array with the next value in your text file. 因此,每次您用文本文件中的下一个值覆盖数组的第一个元素。

This can simply be solved by adding i++; 只需添加i++;即可解决i++; below data_array[i] = input.nextInt(); data_array[i] = input.nextInt();之下data_array[i] = input.nextInt();

Then, I would recommend doing the output and sorting outside of this loop, the whole separation of concerns idea ( Note: ideally all done with different methods or classes depending on the problem, but I will just leave it in the main method here for example purposes). 然后,我建议在此循环外部进行输出和排序,将所有关注点分离注意:理想情况下,根据问题,所有操作都使用不同的方法或类完成,但是我将其留在这里的main方法中,例如目的)。

So therefore, it's better to move the sortArray call outside of the while loop, as currently this will sort the array , then you try to add the next int to the next position, but as the array is in a different order now ( probably ), it will not add it where you think it does. 因此,最好将sortArray调用移到while循环之外,因为当前这将对array排序,然后尝试将下一个int添加到下一个位置,但是由于array现在处于不同的顺序( 可能是 ) ,它不会将其添加到您认为合适的位置。

Another problem you are encountering is, that you aren't writing anything to the dataout file. 您遇到的另一个问题是,您没有向dataout文件写入任何内容。

There are many ways to write to a file, but this is just one example. 写入文件的方法有很多,但这只是一个示例。

java.io.FileWriter fr = new java.io.FileWriter("dataout.txt");
        BufferedWriter br = new BufferedWriter(fr);
        try (PrintWriter output = new PrintWriter(br)) {
            for (int j = 0; j < data_array.length; j++) {
                System.out.println(data_array[j]);
                output.write(data_array[j] + "\r\n");
            }
        }

Then you can calculate your average, and just append it to the end of the file. 然后,您可以计算平均值,并将其附加到文件末尾。

But first, you need to calculate the sum of all the numbers in the array. 但是首先,您需要计算数组中所有数字的总和。

So, instead of creating another loop, you should just add it into your earlier while loop, adding the value with each iteration. 因此,与其创建另一个循环,不如将其添加到您的更早的while循环中,并在每次迭代中添加该值。

sum += data_array[i];

As you're using an array (ie fixed length), you could use the array.length() to get the value for your total variable, or else just add total++; 当您使用array (即固定长度)时,可以使用array.length()来获取total变量的值,或者只添加total++; into the while loop. 进入while循环。

Then your avg = sum / total; 然后,您的avg = sum / total; will work. 将工作。

Full code: 完整代码:

public class NumberSorter {

    public static void main(String[] args) throws Exception {
        double sum = 0;
        double avg = 0;
        double total = 0;
        int i = 0;
        int[] data_array = new int[12];
        java.io.File file = new java.io.File("numbers.txt");
        Scanner input = new Scanner(file);

        while (input.hasNext()) {
            data_array[i] = input.nextInt();
            //add to the sum variable to get the total value of all the numbers
            sum += data_array[i];
            total++;
            //increment the position of 'i' each time
            i++;
        }
        //only sort the array after you have all the elements
        sortArray(data_array);

        //gets the average of all elements of the array
        avg = sum / total;

        java.io.FileWriter fr = new java.io.FileWriter("dataout.txt");
        BufferedWriter br = new BufferedWriter(fr);
        try (PrintWriter output = new PrintWriter(br)) {
            for (int j = 0; j < data_array.length; j++) {
                //write each element plus a new line
                output.write(data_array[j] + "\r\n");
            }
            //write the average (to two decimal places - plus it doesn't allow
            //you to write doubles directly anyway) to the file
            output.write(String.format("%.2f", avg));
            output.close();
        }
    }

    public static void sortArray(int[] data_array) {
        Arrays.sort(data_array);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM