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