3 Replies - 2857 Views - Last Post: 18 October 2010 - 07:01 PM Rate Topic: -----

#1 chryssie0312  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 16-November 08

How do you sort arrays from a text file?

Posted 18 October 2010 - 05:23 PM

Hello all,

I'm having problems trying to sort arrays from a text file: I'm supposed to sort each array in ascending order. So far I was able to sort First Name and Title in order but as to sort the others its not working out. Can you assist? Here's the output of the text file (output1.txt.): I'll show you the initial text file (books.txt.) and my code so far.

I'm new at this, so all i want is help as to how to sort last name, cost price. If you can show me up to there it will be grateful.

Thanks, Chryssie0312


import java.util.*; //Library for Scanner

import java.io.*;   //Library for FileReader


class ReadBooks {

    public static void main(String[] args) {//Starting point of program execution

        int i = 0;
        FileReader fin = null;
        
        int costPrice, sellingPrice, qtySold, qtyStock, reLevel;


        int maxSize = 6; //Maximum size of the array
//LOCAL Array declaration and instantiation

        int costPriceArray[] = new int[maxSize];
        int sellingPriceArray[] = new int[maxSize];
        int qtySoldArray[] = new int[maxSize];
        int qtyStockArray[] = new int[maxSize];
        int reLevelArray[] = new int[maxSize];
        String authorFirstNameArray[] = new String[maxSize];
        String authorLastNameArray[] = new String[maxSize];
        String titleArray[] = new String[maxSize];

  Scanner input, lineInput;
        //try-catch used to catch runtime errors during program execution
        try {
            //creates a file object that points to the physcial file on disk
            fin = new FileReader("C:\\Documents\\books.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Creates a scanner object that can read data from the file object
        input = new Scanner(fin);
        
        String line = "";
        String country = "";
        String authorFirstName = "";
        String authorLastName = "";
        String authorLine = "";
        String titleLine = "";
        String dataLine = "";

        //Prints output table headers
        System.out.printf("\n\n%-15s %-15s %-60s %-15s %-15s %-15s %-15s %-15s", "First name", "Last name", "Title", "Cost Price", "Selling Price", "Stock", "Sold", "Reorder Level");

        int counter = 0;

        while (input.hasNextLine() == true) {

            line = input.nextLine(); //Reads an entire line from the file

            if (line.trim().equalsIgnoreCase("country") == true) {
                System.out.println("");
                country = input.nextLine();
            } else {
                authorLine = line;
                titleLine = input.nextLine();
                dataLine = input.nextLine();

                lineInput = new Scanner(authorLine); //Creates a scanner object
                //to read a author name 

                authorFirstName = lineInput.next(); //Reads a token (firstname)
                //from the string

                authorLastName = lineInput.next();//Reads a token (lastname)
                //from the string

                lineInput = new Scanner(dataLine); //Creates a scanner object
                //to read a price data

                costPrice = lineInput.nextInt();//Reads cp token as an int

                sellingPrice = lineInput.nextInt();//Reads sp token as an int

                qtyStock = lineInput.nextInt();//Reads qstock token as an int

                qtySold = lineInput.nextInt();//Reads qsold token as an int

                reLevel = lineInput.nextInt();//Reads RL token as an int

                //Store data from the input file into the array
                costPriceArray[counter] = costPrice;
                sellingPriceArray[counter] = sellingPrice;
                qtyStockArray[counter] = qtyStock;
                qtySoldArray[counter] = qtySold;
                reLevelArray[counter] = reLevel;
                authorFirstNameArray[counter] = authorFirstName;
                authorLastNameArray[counter] = authorLastName;
                titleArray[counter] = titleLine;
                counter++;

                System.out.printf("\n\n%-15s %-15s %-60s %-15d %-15d %-15d %-15d %-15d", authorFirstName, authorLastName, titleLine, costPrice, sellingPrice, qtyStock, qtySold, reLevel);
            }
        }

        //Creates a Scanner object to read input from the keyboard
        Scanner keyBoard = new Scanner(System.in);
        int menu = 0;
        do {
            //Displays a simple command promt style menu 
            System.out.println("\n\n\nSample Books Inventory Application Menu:");
            System.out.println("Press 1 followed by enter to Sort books by Title:");
            System.out.println("Press 2 followed by enter to Sort books by Author Firstname:");
            System.out.println("Press 3 followed by enter to Sort books by Author Lastname:");
            System.out.println("Press 4 followed by enter to Sort books by Costprice:");
            System.out.println("Press 5 followed by enter to Sort books by Sellingprice:");
            System.out.println("Press 6 followed by enter to Sort books by Books in Stock:");
            System.out.println("Press 7 followed by enter to Sort books by Books Sold:");
            System.out.println("Press 8 followed by enter to Sort books by Reorder Level:");

            System.out.print("\nPlease enter an option from the menu above: ");
            menu = keyBoard.nextInt();


            if (menu == 1) {
                selectionSort(titleArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, authorFirstNameArray, authorLastNameArray);
            } else if (menu == 2) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            } else if (menu == 3) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);

            } else if (menu == 4) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            } else if (menu == 5) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            } else if (menu == 6) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            } else if (menu == 7) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            } else if (menu == 8) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            }
            display(authorFirstNameArray, authorLastNameArray, titleArray, costPriceArray, sellingPriceArray, qtyStockArray,
                    qtySoldArray, reLevelArray);



        } while (menu != 0);
    }

    //To Sort Books and its details in ascending order
    public static void selectionSort(int array1[], int array2[],
            int array3[], int array4[],
            int array5[], String array6[],
            String array7[], String array8[]) {
        int sp;

        for (int p = 0; p < array1.length; p++) {
            sp = p;
            for (int i = sp + 1; i < array1.length; i++) {
                if (array1[sp] > array1[i]) {
                    sp = i;
            swap(array1, p, sp);

            swap(array2, p, sp);
            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);  
             }
           
                
            else if (array2[sp]>array2[i]){
                    sp = i;
                
             swap(array1, p, sp);

            swap(array2, p, sp);
            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);
            }
                else if (array3[sp]>array3[i]){
                    sp = i;
                
            swap(array1, p, sp);

            swap(array2, p, sp);
            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);
                }
                else if (array4[sp]>array4[i]){
                    sp = i;
                
            swap(array1, p, sp);

            swap(array2, p, sp);
            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);
                
                }
                else if (array5[sp]>array5[i]){
                    sp = i;
                
            
            swap(array1, p, sp);

            swap(array2, p, sp);
            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);
        }}
     }
            
           
        
    }

    public static void selectionSort(String array1[], int array6[], int array8[],
            int array3[], int array4[], int array5[], String array7[],
            String array2[]) {

        int sp;
        for (int p = 0; p < array1.length - 1; p++) {
            sp = p;
            for (int i = sp + 1; i <array1.length; i++) {
                if (array1[sp].compareTo(array1[i]) > 0) {
                    sp = i;
                }
                else if (array7[sp].compareTo(array7[i]) > 0) {
                    sp = i;
            }
                else if (array2[sp].compareTo(array2[i]) > 0) {
                    sp = i;
            }
                
            swap(array1, p, sp);

            swap(array2, p, sp);

            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);
        }
        



        }
    }

    public static void swap(int array[], int a, int B)/> {
        int temp = array[a];
        array[a] = array[b];
        array[b] = temp;

    }

    public static void swap(String array[], int a, int B)/> {
        String temp = array[a];
        array[a] = array[b];
        array[b] = temp;

    }

    public static void display(String array6[], String array7[],
            String array8[], int array1[], int array2[],
            int array3[], int array4[], int array5[]) {
        for (int i = 0; i < array1.length; i++) {
          
        System.out.printf("\n%15s %15s %60s %15d %15d %15d %15d %15d",
        array6[i], array7[i], array8[i], array1[i], array2[i], array3[i], array4[i], array5[i]);
                                    
                                }
                            
        }



Edited by Dogstopper: :code:

Attached File(s)


This post has been edited by Dogstopper: 18 October 2010 - 06:49 PM


Is This A Good Question/Topic? 0
  • +

Replies To: How do you sort arrays from a text file?

#2 chryssie0312  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 16-November 08

Re: How do you sort arrays from a text file?

Posted 18 October 2010 - 06:26 PM

I'm trying to sort arrays from a text file. This program is an Book Inventory Program designed to read data (books and the prices) from a file, and from the data given, to sort them in ascending order as well as to add and remove data to and from it. I am very new at this so i'm a bit confused how to do it. I'm not sure if i'm doing it right.However, i was able to sort the title and author's first name. I need help on how to sort the rest and how to add to the file. An example may help. See attached, the text file:(books.txt.) Any help will be greatly appreciated. Thanks chryssie0312. P.S to get a better look at the output i added the output text file.

Here's the code:
 
import java.util.*; //Library for Scanner

import java.io.*;   //Library for FileReader


class ReadBooks {

    public static void main(String[] args) {//Starting point of program execution

        int i = 0;
        FileReader fin = null;
        
        int costPrice, sellingPrice, qtySold, qtyStock, reLevel;


        int maxSize = 6; //Maximum size of the array
//LOCAL Array declaration and instantiation

        int costPriceArray[] = new int[maxSize];
        int sellingPriceArray[] = new int[maxSize];
        int qtySoldArray[] = new int[maxSize];
        int qtyStockArray[] = new int[maxSize];
        int reLevelArray[] = new int[maxSize];
        String authorFirstNameArray[] = new String[maxSize];
        String authorLastNameArray[] = new String[maxSize];
        String titleArray[] = new String[maxSize];

  Scanner input, lineInput;
        //try-catch used to catch runtime errors during program execution
        try {
            //creates a file object that points to the physcial file on disk
            fin = new FileReader("C:\\Users\\admin\\Documents\\School Work\\ICT 2010\\dsal210b\\new1\\books.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Creates a scanner object that can read data from the file object
        input = new Scanner(fin);
        
        String line = "";
        String country = "";
        String authorFirstName = "";
        String authorLastName = "";
        String authorLine = "";
        String titleLine = "";
        String dataLine = "";

        //Prints output table headers
        System.out.printf("\n\n%-15s %-15s %-60s %-15s %-15s %-15s %-15s %-15s", "First name", "Last name", "Title", "Cost Price", "Selling Price", "Stock", "Sold", "Reorder Level");

        int counter = 0;

        while (input.hasNextLine() == true) {

            line = input.nextLine(); //Reads an entire line from the file

            if (line.trim().equalsIgnoreCase("country") == true) {
                System.out.println("");
                country = input.nextLine();
            } else {
                authorLine = line;
                titleLine = input.nextLine();
                dataLine = input.nextLine();

                lineInput = new Scanner(authorLine); //Creates a scanner object
                //to read a author name 

                authorFirstName = lineInput.next(); //Reads a token (firstname)
                //from the string

                authorLastName = lineInput.next();//Reads a token (lastname)
                //from the string

                lineInput = new Scanner(dataLine); //Creates a scanner object
                //to read a price data

                costPrice = lineInput.nextInt();//Reads cp token as an int

                sellingPrice = lineInput.nextInt();//Reads sp token as an int

                qtyStock = lineInput.nextInt();//Reads qstock token as an int

                qtySold = lineInput.nextInt();//Reads qsold token as an int

                reLevel = lineInput.nextInt();//Reads RL token as an int

                //Store data from the input file into the array
                costPriceArray[counter] = costPrice;
                sellingPriceArray[counter] = sellingPrice;
                qtyStockArray[counter] = qtyStock;
                qtySoldArray[counter] = qtySold;
                reLevelArray[counter] = reLevel;
                authorFirstNameArray[counter] = authorFirstName;
                authorLastNameArray[counter] = authorLastName;
                titleArray[counter] = titleLine;
                counter++;

                System.out.printf("\n\n%-15s %-15s %-60s %-15d %-15d %-15d %-15d %-15d", authorFirstName, authorLastName, titleLine, costPrice, sellingPrice, qtyStock, qtySold, reLevel);
            }
        }

        //Creates a Scanner object to read input from the keyboard
        Scanner keyBoard = new Scanner(System.in);
        int menu = 0;
        do {
            //Displays a simple command promt style menu 
            System.out.println("\n\n\nSample Books Inventory Application Menu:");
            System.out.println("Press 1 followed by enter to Sort books by Title:");
            System.out.println("Press 2 followed by enter to Sort books by Author Firstname:");
            System.out.println("Press 3 followed by enter to Sort books by Author Lastname:");
            System.out.println("Press 4 followed by enter to Sort books by Costprice:");
            System.out.println("Press 5 followed by enter to Sort books by Sellingprice:");
            System.out.println("Press 6 followed by enter to Sort books by Books in Stock:");
            System.out.println("Press 7 followed by enter to Sort books by Books Sold:");
            System.out.println("Press 8 followed by enter to Sort books by Reorder Level:");

            System.out.print("\nPlease enter an option from the menu above: ");
            menu = keyBoard.nextInt();


            if (menu == 1) {
                selectionSort(titleArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, authorFirstNameArray, authorLastNameArray);
            } else if (menu == 2) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            } else if (menu == 3) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);

            } else if (menu == 4) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            } else if (menu == 5) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            } else if (menu == 6) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            } else if (menu == 7) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            } else if (menu == 8) {
                selectionSort(authorFirstNameArray, costPriceArray, sellingPriceArray, qtyStockArray,
                        qtySoldArray, reLevelArray, titleArray, authorLastNameArray);
            }
            display(authorFirstNameArray, authorLastNameArray, titleArray, costPriceArray, sellingPriceArray, qtyStockArray,
                    qtySoldArray, reLevelArray);



        } while (menu != 0);
    }

    //To Sort Books and its details in ascending order
    public static void selectionSort(int array1[], int array2[],
            int array3[], int array4[],
            int array5[], String array6[],
            String array7[], String array8[]) {
        int sp;

        for (int p = 0; p < array1.length; p++) {
            sp = p;
            for (int i = sp + 1; i < array1.length; i++) {
                if (array1[sp] > array1[i]) {
                    sp = i;
            swap(array1, p, sp);

            swap(array2, p, sp);
            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);  
             }
           
                
            else if (array2[sp]>array2[i]){
                    sp = i;
                
             swap(array1, p, sp);

            swap(array2, p, sp);
            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);
            }
                else if (array3[sp]>array3[i]){
                    sp = i;
                
            swap(array1, p, sp);

            swap(array2, p, sp);
            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);
                }
                else if (array4[sp]>array4[i]){
                    sp = i;
                
            swap(array1, p, sp);

            swap(array2, p, sp);
            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);
                
                }
                else if (array5[sp]>array5[i]){
                    sp = i;
                
            
            swap(array1, p, sp);

            swap(array2, p, sp);
            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);
        }}
     }
            
           
        
    }

    public static void selectionSort(String array1[], int array6[], int array8[],
            int array3[], int array4[], int array5[], String array7[],
            String array2[]) {

        int sp;
        for (int p = 0; p < array1.length - 1; p++) {
            sp = p;
            for (int i = sp + 1; i <array1.length; i++) {
                if (array1[sp].compareTo(array1[i]) > 0) {
                    sp = i;
                }
                else if (array7[sp].compareTo(array7[i]) > 0) {
                    sp = i;
            }
                else if (array2[sp].compareTo(array2[i]) > 0) {
                    sp = i;
            }
                
            swap(array1, p, sp);

            swap(array2, p, sp);

            swap(array3, p, sp);
            swap(array4, p, sp);
            swap(array5, p, sp);
            swap(array6, p, sp);
            swap(array7, p, sp);
            swap(array8, p, sp);
        }
        



        }
    }

    public static void swap(int array[], int a, int B)/> {
        int temp = array[a];
        array[a] = array[b];
        array[b] = temp;

    }

    public static void swap(String array[], int a, int B)/> {
        String temp = array[a];
        array[a] = array[b];
        array[b] = temp;

    }

    public static void display(String array6[], String array7[],
            String array8[], int array1[], int array2[],
            int array3[], int array4[], int array5[]) {
        for (int i = 0; i < array1.length; i++) {
          
        System.out.printf("\n%15s %15s %60s %15d %15d %15d %15d %15d",
        array6[i], array7[i], array8[i], array1[i], array2[i], array3[i], array4[i], array5[i]);
                                    
                                }


Here is how the output looks like:
First name   Last name       Title    Cost Price      Selling Price   Stock     Sold     Reorder    


Vidiadhar Naipaul  Between Father and Son: Family Letters 65   85     25   25           10              

Earl  Lovelace     The Dragon Can't Dance       75    90       45      55           35               

Gérard  Besson     Folklore & Legends of Trinidad and Tobago  45    55    20  5            20                    


Joseph  Conrad   Heart of Darkness (Dover Thrift Editions) 66 89  47 21            50                   

Charles         Dickens         Great Expectations (Penguin Classics) by           63              91              74              12            15             

Charles         Dickens         David Copperfield (Modern Library Classics)       45              102             56              45              20           


Sample Books Inventory Application Menu:
Press 1 followed by enter to Sort books by Title:
Press 2 followed by enter to Sort books by Author Firstname:
Press 3 followed by enter to Sort books by Author Lastname:
Press 4 followed by enter to Sort books by Costprice:
Press 5 followed by enter to Sort books by Sellingprice:
Press 6 followed by enter to Sort books by Books in Stock:
Press 7 followed by enter to Sort books by Books Sold:
Press 8 followed by enter to Sort books by Reorder Level:

Please enter an option from the menu above: 
1

      


Attached File(s)


Was This Post Helpful? 0
  • +
  • -

#3 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,051
  • Joined: 15-July 08

Re: How do you sort arrays from a text file?

Posted 18 October 2010 - 06:58 PM

Honestly, it will be an absolute pain to sort these because you have so many parallel arrays. You should honestly look into using arrays of objects.

macosxnerd101 has a good tutorial on that:
http://www.dreaminco...arallel-arrays/

After that, you should make the class implement Comparable interface so that you merely have to call Arrays.sort() on it and it will be done.

edit: Oh, and duplicate topics merged. Please do not post more than one topic on the same subject.

This post has been edited by Dogstopper: 18 October 2010 - 06:59 PM

Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10805
  • View blog
  • Posts: 40,278
  • Joined: 27-December 08

Re: How do you sort arrays from a text file?

Posted 18 October 2010 - 07:01 PM

Don't use Parallel Arrays. Design a Book class instead to encapsulate authorFirstName, authorLastName, title, etc. Then use the Comparable interface (implement with Book), or a custom Comparator (see the java.util.Comparator interface) to pass to Arrays.sort(), along with your Book[]. It's much more encapsulated, OO, and a lot easier to sort by.

For more information on class design, you shoudl check out my tutorial Moving Away From Parallel Arrays.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1