Sorting Arrays to a file Java

  • Comp Sci
  • Thread starter thatguy101
  • Start date
  • #1
14
0

Homework Statement


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

Homework 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

The Attempt at a Solution


Code:
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!!:)
 

Answers and Replies

  • #2
34,673
10,815
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?
if(event[i] != 1892 && (readin.hasNext() == false)){
event = addElement(event, 1892);
}
You are in the "if (event[i] == 1892)" condition - this cannot be true. Also, where would be the point of this part?
 
  • #3
14
0
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?
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!
 
  • #4
gabbagabbahey
Homework Helper
Gold Member
5,002
6
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!
Hi TG101,

As Mfb pointed out,

You are in the "if (event[i] == 1892)" condition - this cannot be true.
Code:
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);              
        }             
    }               
}
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:
  • #5
14
0
Thank you! I believe I have found a solution. Your help is very much appreciated!!
 
  • #6
14
0
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:
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;
       
    }
}
 
  • #7
gabbagabbahey
Homework Helper
Gold Member
5,002
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:
            //make sure it exsits
            if(file.exists()){
                {
Why the second opening bracket { ?

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

Code:
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);
    }
}
It looks like you are checking your boolean while still inside your for loop...is that really what you intended?

Code:
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]);
}
Careful, when adding 1892 you might destroy your sort order in your event[] array
 

Related Threads on Sorting Arrays to a file Java

  • Last Post
Replies
4
Views
2K
Replies
10
Views
6K
Replies
12
Views
3K
  • Last Post
Replies
6
Views
2K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
7
Views
7K
  • Last Post
Replies
6
Views
3K
  • Last Post
Replies
1
Views
5K
  • Last Post
Replies
6
Views
6K
Top