简体   繁体   中英

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. 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. 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++; below 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).

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.

Another problem you are encountering is, that you aren't writing anything to the dataout file.

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.

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++; into the while loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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