简体   繁体   中英

Java sorting text file with Comparable

I need a program that reads in data and sorts the file in descending order using quicksort based on the index provided for instance this is the data using comparable

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

And i need to sort by the 5th index(mmax) case 2 and the 6th(cache) case 3 and the ninth index(php) case 4 in descending order & print the first index which is already sorted case 1 The problems with my code are as follows:

  • It doesn't sort based off the index
  • It gives me an error at runtime with the code: Arrays.sort(c) ;

Please help with suggestions Thanks

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

Comparator class:

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

The biggest problem is that the Computer classes do not get instantiated for each line that gets read.

As you want to have different sort options depending on the user input, you can not let the Computer class determine the compare method, but instead you will need to create a separate Comparator implementation for each sort option. Next, make the file read operation generic and abstract it away in a separate method call from each selected case. Instead of an array of Computers, I would make it a List or a Set, because you don't (want to) know the length up front.

I would like to lay out the steps in detail so that you could figure out each step for yourself. You have got a lot of it right.. but there are gaps.

  1. Create a Computer class. It should have a constructor which takes a single String and splits it using the separator ',' and parses each part to String/int as applicable. (It would be preferable for you to parse and store the whole string.. which means you can have 10 fields in your class)
  2. Create a blank ArrayList to store the Computer objects.
  3. Iterate through the file and readLine
  4. Call the Computer constructor using the String representing each line in the file within the while loop
  5. Add the new Computer object to the computers ArrayList
  6. Write 5 different comparators.
  7. Based on user input, instantiate the correct comparator and pass it to the sort method
  8. Print the sorted array

If you still face a problem, mention the specific point at which you like more clarity..

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