简体   繁体   English

如何从一个文本文件中读取整数,将它们从最小到最大排序,然后将它们写入另一个文本文件

[英]How to read integers from one text file, sort them from least to greatest, and then write them to another text file

I am attempting to write 100 random integers to one text file, sort them from least to greatest, and then write those numbers, sorted, to a separate text file.我试图将 100 个随机整数写入一个文本文件,将它们从最小到最大排序,然后将这些数字排序后写入一个单独的文本文件。 I understand how to write the numbers to one file, and how to sort them.我了解如何将数字写入一个文件,以及如何对它们进行排序。 Both files must be created by the program if they do not already exist.如果这两个文件尚不存在,则必须由程序创建它们。 For instance if the "Numbers.txt" that I write the original 100 random integers on does not exist, the program will create the file for me, as same goes for the text file I am attempting to write the sorted numbers on.例如,如果我在其上写入原始 100 个随机整数的“Numbers.txt”不存在,程序将为我创建该文件,就像我试图在其上写入排序数字的文本文件一样。 I am struggling to understand how to write the sorted numbers from one file to another.我正在努力理解如何将排序的数字从一个文件写入另一个文件。

I have attempted to take the same numbers from the integer array that the numbers are originally stored in, and sort it with the Arrays.sort command, and then write that information to the separate file which I wish to be called "Sorted.txt".我试图从最初存储数字的整数数组中获取相同的数字,并使用 Arrays.sort 命令对其进行排序,然后将该信息写入我希望称为“Sorted.txt”的单独文件中. I run into a problem there where I get an incompatible type error, stating void cannot be converted to int, but do not know how to fix this error in logic.我在那里遇到了一个问题,我得到了一个不兼容的类型错误,说明 void 不能转换为 int,但不知道如何在逻辑上修复这个错误。

import java.util.*;
import java.io.*;

public class Numbers {
   public static void main(String[] args) throws Exception {
      //check if source file exists
      File number = new File("Numbers.txt");
      File sorted = new File("Sorted.txt");
      if (!number.exists()) {
         try ( // create the file
         PrintWriter output = new PrintWriter(number);
         ) {
            for (int i = 0; i <= 100; i++) {
               output.print(((int)(Math.random() * 999) + 1) + " ");
            }
         }
      }
      try (
      Scanner input = new Scanner(number);
      ) {
         int[] numbers = new int[100];
         for (int i = 0; i < 100; i++)
            System.out.print(numbers[i] + " ");

            System.out.println();

            if (!sorted.exists()) {
               try (
               PrintWriter output = new PrintWriter(sorted)
               ) {
                  for (int i = 0; i < 100; i ++) {
                     output.print((int)Arrays.sort(numbers));
                  }
            }
         }
      }
   }
}

The expected result is that the first text file shows the numbers as they were when they were randomly created, while the second text file shows them after they are sorted.预期的结果是第一个文本文件显示的是随机创建时的数字,而第二个文本文件显示的是排序后的数字。 As of current, I can get the first file to show the numbers in a random order, but cannot even get the second text file to be created, let alone the numbers sorted and wrote on it.截至目前,我可以获得第一个文件以随机顺序显示数字,但甚至无法创建第二个文本文件,更不用说在其上排序和写入的数字了。

Arrays.sort returns void ( see doc ). Arrays.sort 返回 void( 参见文档)。

What you could do is sort the array.你可以做的是对数组进行排序。 Arrays.sort(numbers);

And after write the result to a file.然后将结果写入文件。

for (int i = 0; i < 100; i ++) {
    output.print(numbers[i] + " ");
}

Complete Example:完整示例:

import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;


public class Numbers {
   public static void main(String[] args) throws Exception {
      //check if source file exists
      File number = new File("Numbers.txt");
      File sorted = new File("Sorted.txt");
      if (!number.exists()) {
         try ( // create the file
         PrintWriter output = new PrintWriter(number);
         ) {
            for (int i = 0; i <= 100; i++) {
               output.print(((int)(Math.random() * 999) + 1) + " ");
            }
         }
      }
      try (
      Scanner input = new Scanner(number);
      ) {
         int[] numbers = new int[100];
         for (int i = 0; i < 100; i++) {

             numbers[i] = input.nextInt();           
         }
        if (!sorted.exists()) {
           try (
           PrintWriter output = new PrintWriter(sorted)
           ) {
              Arrays.sort(numbers);
              for (int i = 0; i < 100; i ++) {
                 output.print(numbers[i] + " ");
              }
        }
     }
  }
} }

I would suggest extracting to a method the code that writes to the file.我建议将写入文件的代码提取到方法中。 Since it would only need a path and content it can be reused for both files and it will make your life way easier.由于它只需要一个路径和内容,因此可以对这两个文件重复使用,这将使您的生活更轻松。

It is also very helpful if you include the line number where you get the error since it's not always clear where the exception is thrown.如果您包含出现错误的行号,这也非常有帮助,因为并不总是清楚抛出异常的位置。

From what I understood from your question the problem is about generating some numbers, write them to a file and lastly sort them and write them to another file.从我从你的问题中了解到的问题是关于生成一些数字,将它们写入一个文件,最后对它们进行排序并将它们写入另一个文件。 I wrote some code using the same approach but a bit more restructured.我使用相同的方法编写了一些代码,但结构有所调整。 I hope it helps.我希望它有帮助。

public static void main(String[] args) {
    int[] randomData = new Random().ints(100).toArray();//just a short way to generate numbers. Use your own.

    File numbers = writteArray("Numbers.txt", randomData);
    Arrays.sort(randomData);
    File sorted = writteArray("Sorted.txt", randomData);
}

public static File writteArray(String Path, int[] randomNumbers){
    File numbers = new File(Path);
    //if the file does not exist it will be created automatically
    try(PrintWriter fileWritter = new PrintWriter(numbers)) {
        //just an example of how to write them. Use your prefered format
        //also you can use the append function to not lose the previous content
        for (int e : randomNumbers)
            fileWritter.printf(" %d", e);
        fileWritter.println();
    }
    catch (FileNotFoundException e){
        e.printStackTrace(); 
    }
    return numbers;
}

As an edit you can make the writeArray() function return void if you don't need the files after.作为编辑,如果您之后不需要这些文件,您可以使 writeArray() 函数返回 void。

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

相关问题 从文本文件中读取整数并将它们存储到 Java 中的数组中 - Read integers from a text file and store them into an array in Java 从文本文件中读取行,并通过将行中的值写入新的文本文件中以均值(平均值)对行进行排序 - Read rows from a text file and sort the values from rows by mean (average) by writing them in a new text file 如何从文本文件排序并写入另一个文本文件Java - How to sort from text file and write into another text file Java 从文本文件中读取整数并将它们放入对象中以存储到散列映射中 - Reading integers from a text file and putting them into objects to store into a hashmap 从文本文件中读取整数并将其放入已排序的数组中 - Reading integers from a text file and putting them into a sorted array 从文本文件中读取整数并添加它们 - Reading only integers from text file and adding them 从文本文件中读取,排序并重新写入 - Read from a text file, sort it, and write it again 尝试读取值并将其从最大到最小 - attempting to read values and putting them from greatest to least (Java) 如何将数字从小到大排序并将它们分配给变量? - (Java) How Do I Sort Numbers From Least to Greatest and Assign Them to Variables? Java:从现有的文本文件中读取整数并输出到另一个文件 - Java: Read integers from an existing text file and output to another file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM