How to Save and Sort a List of Historical Events in Java?

In summary, this program reads in a list of years from a file, sorts them in descending order, and checks if the founding of CMU in 1892 is included in the list. If it is not, it adds it to the list and writes the updated list to a new file.
  • #1
thatguy101
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!:)
 
Physics news on Phys.org
  • #2
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?
thatguy101 said:
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
mfb said:
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
thatguy101 said:
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,

mfb said:
You are in the "if (event[i] == 1892)" condition - this cannot be true.

thatguy101 said:
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
Thank you! I believe I have found a solution. Your help is very much appreciated!
 
  • #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:
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
thatguy101 said:
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

thatguy101 said:
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?

thatguy101 said:
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 to How to Save and Sort a List of Historical Events in Java?

1. How do I sort an array in Java?

In Java, you can use the Arrays.sort() method to sort an array in ascending order. This method takes in the array as a parameter and modifies it in place. For example:
int[] numbers = {5, 2, 8, 1};
Arrays.sort(numbers); // numbers will now be {1, 2, 5, 8}

2. How can I sort an array in descending order?

To sort an array in descending order, you can use the Arrays.sort() method with a custom comparator. The comparator will compare elements in reverse order, resulting in a descending order sort. For example:
int[] numbers = {5, 2, 8, 1};
Arrays.sort(numbers, Collections.reverseOrder()); // numbers will now be {8, 5, 2, 1}

3. How do I sort an array of objects in Java?

To sort an array of objects in Java, you can use the Arrays.sort() method with a custom comparator. The comparator will compare the objects based on a specific attribute or field and sort them accordingly. For example:
Person[] people = {new Person("John", 25), new Person("Jane", 30)};
Arrays.sort(people, (p1, p2) -> p1.getAge() - p2.getAge()); // sort by age in ascending order

4. Can I sort an array based on multiple criteria?

Yes, you can sort an array based on multiple criteria by using a custom comparator that compares multiple attributes or fields of the objects. You can also use the Comparator.thenComparing() method to specify a secondary comparator to use in case the first one results in a tie. For example:
Person[] people = {new Person("John", 25), new Person("Jane", 30)};
Arrays.sort(people, Comparator.comparing(Person::getAge).thenComparing(Person::getName)); // sort by age, then by name

5. How do I save a sorted array to a file in Java?

To save a sorted array to a file in Java, you can use a FileWriter or BufferedWriter to write the sorted array elements to the file. You can also use the Arrays.toString() method to convert the array to a string and then write it to the file. For example:
int[] numbers = {5, 2, 8, 1};
Arrays.sort(numbers);
FileWriter writer = new FileWriter("file.txt");
writer.write(Arrays.toString(numbers));
writer.close();

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
18
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
11
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
10K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
11
Views
11K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
5K
  • Programming and Computer Science
Replies
13
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
Back
Top