简体   繁体   English

用数组将数字写入文件,然后按顺序打印

[英]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. 这是针对大学Java 2作业的,我觉得我应该知道这一点,但我正在空白。

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: 首先,程序在此处检查src文件中是否存在某个文件:

        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: 然后,如果找不到该文件,我们将创建它并在此处从0到100写入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: 我尝试在两个地方输入Array.sort(randomArray):

                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循环来做到这一点:

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]);       
}

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

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