【问题标题】:Java sorting text file with ComparableJava 使用 Comparable 对文本文件进行排序
【发布时间】:2026-01-03 22:30:02
【问题描述】:

我需要一个程序来读取数据并根据提供的索引使用快速排序对文件进行降序排序,例如这是使用可比较的数据

adviser,32/60,125,256,6000,256,16,128,198,199
amdahl,470v/7,29,8000,32000,32,8,32,269,253
amdahl,470v/7a,29,8000,32000,32,8,32,220,253
amdahl,470v/7b,29,8000,32000,32,8,32,172,253
amdahl,470v/7c,29,8000,16000,32,8,16,132,132

我需要按第 5 个索引(mmax)案例 2 和第 6 个(缓存)案例 3 和第 9 个索引(php)案例 4 以降序排序 & 打印已经排序的第一个索引案例 1 我的代码的问题如下:

  • 它不根据索引进行排序
  • 它在运行时给我一个错误代码:Arrays.sort(c);

请提供建议 谢谢

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

public class Prog4 {
    static Scanner input;
    static File filename;
    /**
     * This function displays the menu for the user to choose an option from 
     */
    public void menu() {
        System.out.println("Option 1: Sort by VENDOR: ");
        System.out.println("Option 2: Sort decreasing number by MMAX: ");
        System.out.println("Option 3: Sort decreasing number by CACH: ");
        System.out.println("Option 4: Sort decreasing number by PRP: ");
        System.out.println("Option 5: Quit program");
    }

    /**
      * Constructor to handle the cases in the menu options
      * @throws FileNotFoundException 
      * @throws IOException 
      */
    public Prog4() throws FileNotFoundException {
        //Accepts user input
        Scanner in = new Scanner(System.in);

        //calls the menu method
        menu();

        //Initializes the run variable making the program loop until the user terminates the program
        Boolean run = true;

        //While loop
        while (run) {
            switch (in.nextInt()) {
            case 1:
                System.out.println("Option 1 selected");
                System.out.println("Sorted by vendor:");

                filename = new File("machine.txt");
                //Instantiate Scanner s with f variable within parameters
                //surround with try and catch to see whether the file was read or not
                try {
                    input = new Scanner(filename);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                //Instantiate a new Array of String type
                String array [] = new String[10];
                //while it has next ..
                while (input.hasNext()) {
                //Initialize variable 
                int i = 0;
                //store each word read in array and use variable to move across                                                               array                     array[i] = input.next();
                    //print 
                    System.out.println(array[i]);
                    //so we increment so we can store in the next array index
                    i++;
                }

            case 2:
                System.out.println("Press any key to continue");
                Scanner input2 = new Scanner(System.in);
                String x = input2.nextLine();
                if (x.equals(0)) continue;
                System.out.println("Option 2 selected") ;

                Computer[] c = new Computer[10];
                filename = new File("machine.txt");

                try {
                input = new Scanner(filename);
                } catch (FileNotFoundException e) {
                e.printStackTrace();
                }
                Arrays.sort(c);
                while (input.hasNextLine()) {
                    for (int i = 0; i < c.length; i++) {
                        System.out.println(c[i]);
                    }
                }
            }
        }
    }

    /**
      * Main method
      * @param args
      * @throws FileNotFoundException 
      */
    public static void main(String[] args) throws FileNotFoundException {
        //Calls the constructor
        new Prog4();
        //static Scanner input;
    }

    public static void quickSort(int arr[], int left, int right) {
        if (left < right) {
            int q = partition(arr, left, right);
            quickSort(arr, left, q);
            quickSort(arr, q+1, right);
        }
    }

    private static int partition(int arr[], int left, int right) { 
        int x = arr[left];
        int i = left - 1;
        int j = right + 1;
        while (true) {
            i++;
            while (i < right && arr[i] < x)
                i++;
            j--;
            while (j > left && arr[j] > x)
                j--;
            if (i < j)
                swap(arr, i, j);
            else
                return j;
            }
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

比较器类:

import java.util.Comparator;

class Computer implements Comparable<Computer> {

    private String vendor;
    private int mmax;
    private int cach;
    private int php;

    public Computer(int value) {
        this.mmax = value;
    }

    public String getVendor() {
        return vendor;
    }

    public void setVendor(String vendor) {
        this.vendor = vendor;
    }

    public int getMmax() {
        return mmax;
    }

    public void setMmax(int mmax) {
        this.mmax = mmax;
    }

    public int getCach() {
        return cach;
    }

    public void setCach(int cach) {
        this.cach = cach;
    }

    public int getPhp() {
        return php;
    }

    public void setPhp(int php){
        this.php = php;
    }

    @Override
    public int compareTo(Computer m) {
        if (mmax < m.mmax) {
            return -1;
        }

        if (mmax > m.mmax) {
            return 1;
        }

        // only sort by height if age is equal
        if (cach > m.cach) {
            return -1;
        }

        if (cach < m.cach) {
            return 1;
        }
        if (php > m.php) {
            return -1;
        }

        if (php < m.php) {
            return 1;
        }
        return 0;
    }

    public static Comparator<Computer> ComparemMax = new Comparator<Computer>() {
        @Override
        public int compare(Computer p1, Computer p2) {
            return p2.getMmax() - p1.getMmax();
        }
    };
}

【问题讨论】:

  • 打印“null”10次吗?
  • 不,它会打印一个包含 10 个索引但价值几行的数组

标签: java file sorting


【解决方案1】:

最大的问题是计算机类没有为读取的每一行实例化。

由于您希望根据用户输入具有不同的排序选项,因此您不能让 Computer 类确定比较方法,而是需要为每个排序选项创建单独的 Comparator 实现。接下来,使文件读取操作通用,并在每个选定案例的单独方法调用中将其抽象出来。我会将其设为列表或集合,而不是计算机数组,因为您不(不想)预先知道长度。

【讨论】:

  • List c = new ArrayList();我试图这样做,然后用这一行调用它,但它打印出 nothingCollections.sort(c); while(input.hasNextLine()) { for(String s: c) System.out.println(s); }
  • 没错,因为您的代码中没有任何new Computer(),并且没有任何内容添加到数组/列表中。
  • 我使用了这段代码,但现在它打印出所有的 0,这至少是一个步骤 List c = new ArrayList();文件名 = 新文件(“machine.txt”);尝试{输入=新扫描仪(文件名); } catch (FileNotFoundException e) { e.printStackTrace(); } 计算机 e1=新计算机(输入); c.add(e1); while(input.hasNextLine()) { for(Computer computer:c) System.out.println(computer.getMmax()); }
【解决方案2】:

我想详细列出这些步骤,以便您自己弄清楚每个步骤。你有很多正确的..但是有差距。

  1. 创建一个计算机类。它应该有一个构造函数,它接受一个字符串并使用分隔符“,”将其拆分,并将每个部分解析为适用的字符串/int。 (您最好解析和存储整个字符串。这意味着您的类中可以有 10 个字段)
  2. 创建一个空白 ArrayList 来存储计算机对象。
  3. 遍历文件并读取行
  4. 在 while 循环中使用代表文件中每一行的字符串调用 Computer 构造函数
  5. 将新的计算机对象添加到计算机数组列表中
  6. 编写 5 个不同的比较器。
  7. 根据用户输入,实例化正确的比较器并将其传递给排序方法
  8. 打印排序后的数组

如果您仍然遇到问题,请提及您希望更清晰的具体点。

【讨论】:

    最近更新 更多