简体   繁体   中英

Writing numbers to a file with an array then printing them sorted

I am working with reading/writing files using arrays. This is for a college Java 2 assignment, I feel like I should know this but I'm drawing a blank.

What I need to do is sort the numbers in the file in ascending order.

First, the program checks if a certain file exits within the src file here:

        File file = new File("src/chapter12/randomfile.dat"); //File path

    if(file.exists())
    {   //If the file exists, print out each element on the file.
        Scanner input = new Scanner(file);
        while(input.hasNextLine())
        {               
            System.out.println(input.nextLine());
        }
            input.close();
    }

^^ This part works out perfectly for searching for the file, then if it is found printing out the lines it contains.

Then, if the file is not found we create it and write 100 random numbers to it here, from 0-100:

else
    {   //If the file isn't found, create it and write 100 random numbers to it.
        try(PrintWriter output = new PrintWriter(file))
        {
            for(int i = 0; i < size; i++)
            {
                randomArray[i] += random.nextInt(101);
                output.print(randomArray[i] + " ");
            }
        }

I have tried inputting Array.sort(randomArray) in two places:

                randomArray[i] += random.nextInt(101);
                output.print(randomArray[i] + " ");
                Arrays.sort(randomArray);

and here

Scanner input = new Scanner(file);
        Arrays.sort(randomArray);
        while(input.hasNextLine())
        {               
            System.out.println(input.nextLine());
        }
            input.close();

The first location is in the loop, where it would sort it before the end of each iteration. The second one is before I do the check for the file, because the first time the program runs, the file doesn't exist so the array is empty. However since the file is created after the first run, logically it would sort the already full array before reading the file, but it made no sense because it would sort the array, but since the file is created, it can't sort the file.

Currently I am trying to search a way to possibly sort the file before printing out what was read, however my assignment states "You can use the array class to sort the file." This is where I draw a blank, any suggestions?

Here is a full snippet of code if needed:

package chapter12;

import java.io.*;           //Allows us to use File Writer.
import java.util.Arrays;    //Allows us to sort the array.
import java.util.Random;    //Allows us to get random numbers.
import java.util.Scanner;   //Allows us to read the file.
public class Excercise1215 
{
    public static void main(String[] args) throws FileNotFoundException 
    {
        int size = 100;
        int[] randomArray = new int[size];
        Random random = new Random();

    File file = new File("src/chapter12/randomfile.dat"); //File path

    if(file.exists())
    {   //If the file exists, print out each element on the file.
        Scanner input = new Scanner(file);
        Arrays.sort(randomArray);
        while(input.hasNextLine())
        {               
            System.out.println(input.nextLine());
        }
            input.close();
    }
    else
    {   //If the file isn't found, create it and write 100 random numbers to it.
        try(PrintWriter output = new PrintWriter(file))
        {
            for(int i = 0; i < size; i++)
            {
                randomArray[i] += random.nextInt(101);
                output.print(randomArray[i] + " ");
                Arrays.sort(randomArray);
            }
        }           
        //Exception handling
        catch(FileNotFoundException ex)
        {
            System.out.println("File was not found.");  
        }
        catch(Exception ex)
        {
            System.out.println("Something went wrong.");
        }
    }
}

}

Before writing to the file if it doesn't exist, you should sort your array before writing it. Do this using two for loops like this:

for(int i = 0; i < size; i++) {
    randomArray[i] += random.nextInt(101); //Populate the array
}
Arrays.sort(randomArray); // Sort the array
for(int i = 0; i < size; i++) {
    output.print(randomArray[i] + " "); // Write the array to the file
}

If the file does exist you should read the values into your array, sort the array, then print the array. Here is a sample:

if(file.exists())
{   //If the file exists, print out each element on the file.
    Scanner input = new Scanner(file);
    int count = 0;
    while(input.hasNextInt())
    {
        randomArray[count++] = input.nextInt();
    }
    input.close();
    Arrays.sort(randomArray);

    for(int i = 0; i < size; i++) {
        System.out.println(randomArray[i]);
    }
}

You code should be something like this when reading in your unsorted file

 Scanner input = new Scanner(file);
 i = 0;
 while(input.hasNextInt())
{               
     // add to randomArray
     randomArray[i++] = input.nextInt();
}

Arrays.sort(randomArray);

// now iterate your sorted array and print out 
for (i = 0; i < randomArray.length; i++) {
   System.out.println(randomArray[i]);       
}

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