1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Sorting Arrays to a file Java

  1. Apr 22, 2015 #1
    1. The problem statement, all variables and given/known data
    You are provided the following list that contains (semi-random) years from modern history. Save the list to a text file named “events.txt” Write a program that: 1. Reads in the file “events.txt” 2. Sorts it with the latest events first 3. Determines whether the founding of CMU in 1892 was considered a world historic event 4. If not so yet, adds the event to the list of events 5. Writes the new list of events to a file named “sorted_events.txt

    2. Relevant equations
    I am able to read events.txt just fine, I just don't know how to get the new array onto sorted_events.txt.
    ANd 1892 is not on the list

    3. The attempt at a solution
    Code (Text):

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


    public class Assignment {
        public static void main(String[] args) throws FileNotFoundException{
           
            File file =new File("events.txt");
            FileReader read = new FileReader(file);
               LineNumberReader lines = new LineNumberReader(read);
               Scanner readin = new Scanner(file);
               PrintWriter output = new PrintWriter("sorted_events.txt");

            try{
           
                //call for the file
               
     //make sure it exsits
                if(file.exists()){

                    //first write this to determine the number of lines
                   int linenumber = 0;
                   //gets the number of lines
                       while (lines.readLine() != null){
                      linenumber++;
                       }
                       int[] event = new int[linenumber];
                       int j = 0;
                       while(readin.hasNext()){
                         
                          event[j]=readin.nextInt();
                          j++;
                         
                       }
                       //sort the array
                       Arrays.sort(event);
                       for(int i = 0; i < event.length; i++){
                          if (event[i] == 1892){
                              //see if 1892 is on the list
                              System.out.println("CMU is a historic event");
    //(I think her is where my issue is
                          if(event[i] != 1892 && (readin.hasNext() == false)){
                              event = addElement(event, 1892);
                                 
                              }
                                 
                             
                          }
                       
                       }
                       for(int print = 0 ; print < event.length; print++){
                          output.println(event[print]);
                       }
                       readin.close();
                       output.close();
                       lines.close();
                       
                       


                }else{
                    System.out.println("File does not exists!");
                }

            }catch(IOException e){
                e.printStackTrace();
            }

        }

        static int[] addElement(int[] a, int e) {
           a  = Arrays.copyOf(a, a.length + 1);
           a[a.length - 1] = e;
           return a;
           
        }
    }
     
    Any help would be greatly appreciated!!:)
     
  2. jcsd
  3. Apr 22, 2015 #2

    mfb

    User Avatar
    2016 Award

    Staff: Mentor

    Did you check that "events" gets filled properly? I'm not sure what the readLine/nextInt things will do in Java (you are reading all lines before you start filling events). What is the result of the output of all events?
    You are in the "if (event[i] == 1892)" condition - this cannot be true. Also, where would be the point of this part?
     
  4. Apr 22, 2015 #3
    The array events does get filled. I used a for loop with System.out.println(); to check it before I went on.
    As for the "if (event != 1892 && (readin.hasNext() == false))" I thought I might need that to let the program know that the year 1892 needs to be added to the list. Like I said, this is the part I am unsure about.
    Thank you for the reply!
     
  5. Apr 23, 2015 #4

    gabbagabbahey

    User Avatar
    Homework Helper
    Gold Member

    Hi TG101,

    As Mfb pointed out,

    Your second "if" statement is inside the first and will never evaluate to true.

    Moreover, if it were outside the first "if" statement it would not do what you are hoping. Rather than only adding 1892 to the Array if it is not already present, it will add it to the Array as long as the last entry is not 1892. Instead, if you are going to use your for loop to search for 1892, you probably want to have a boolean variable to indicate whether it is found in the Array: Initialize the variable before the loop, set it to true inside the loop if 1892 is found, and then check it after the loop to determine whether you need to add 1892 to the list.

    Better still, as you have a sorted Array, why not try utilizing the binarySearch method to look for 1892 rather than looping through the entire Array sequentially?

    One final note is that I think you are sorting your Array in the wrong order given that the assignment asks you to output the values with the most recent event first.
     
    Last edited: Apr 23, 2015
  6. Apr 23, 2015 #5
    Thank you! I believe I have found a solution. Your help is very much appreciated!!
     
  7. Apr 23, 2015 #6
    So I was able to make the array go from latest event on down, but I can't find how to add 1892, or where my PrintWriter is writing to.
    Here's my newish code
    Code (Text):

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


    public class Assignment {
        public static void main(String[] args) throws FileNotFoundException{
           
            File file =new File("events.txt");
            FileReader read = new FileReader(file);
               LineNumberReader lines = new LineNumberReader(read);
               Scanner readIn = new Scanner(file);
               PrintWriter output = new PrintWriter("sorted_events.txt");

            try{
           
                //call for the file
               
     //make sure it exsits
                if(file.exists()){
                    {
                    //first write this to determine the number of lines
                   int lineNumber = 0;
                   //gets the number of lines
                       while (lines.readLine() != null){
                      lineNumber++;
                       }
                       int[] event = new int[lineNumber];
                       int j = 0;
                       while(readIn.hasNext()){
                         
                          event[j]=readIn.nextInt();
                          j++;
                         
                       }
                       //sort the array
                       Arrays.sort(event);
                       boolean found = false;
                       for(int i = 0; i < event.length; i++){
                          if (event[i] == 1892){
                              //see if 1892 is on the list
                              System.out.println("CMU is a historic event");
                              found= true;
                          }
                       
                          if (found == false){
                              addElement(event, 1892);
                          }
                          }
                          int[] sortedEvent = new int[lineNumber];
                       for(int k = 0; k < event.length; k++){
                          sortedEvent[k] = event[(event.length-1) - k];
                       System.out.println(sortedEvent[k]);
                       }
                       for(int print = 0 ; print < event.length; print++){
                          output.println(sortedEvent[print]);
                       
                       }
                }
                       readIn.close();
                       output.close();
                       lines.close();
                       
                       


                }else{
                    System.out.println("File does not exists!");
                }
                }
                catch(IOException e){
                e.printStackTrace();
            }

        }

        static int[] addElement(int[] a, int e) {
           a  = Arrays.copyOf(a, a.length + 1);
           a[a.length - 1] = e;
           return a;
           
        }
    }
     
     
  8. Apr 23, 2015 #7

    gabbagabbahey

    User Avatar
    Homework Helper
    Gold Member

    Why the second opening bracket { ?

    Your PrintWriter is probably writing to whatever directory your .java file is stored in

    It looks like you are checking your boolean while still inside your for loop...is that really what you intended?

    Careful, when adding 1892 you might destroy your sort order in your event[] array
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Sorting Arrays to a file Java
  1. Arrays in Java (Replies: 3)

  2. Sorting Array (Replies: 6)

Loading...