import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; public class DateSorter { public static void main(String[] args) { System.out.println("What do you want to do?\n\t1. Write Dates?\n\t2. Sort Dates?"); boolean write = false; try { int input = System.in.read(); if (input == '1') { write = true; } else { write = false; } } catch (IOException e) { e.printStackTrace(); } long currentTime = System.currentTimeMillis(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); NumberFormat numFormat = NumberFormat.getNumberInstance(); numFormat.setMaximumFractionDigits(2); numFormat.setMinimumFractionDigits(2); numFormat.setMaximumIntegerDigits(0); if (write) { try { PrintStream out = new PrintStream("temp.txt"); for (int i = 0; i < 500; i++) { double num = Math.random(); long randomTime = (long)(currentTime * num); out.println(numFormat.format(num) + " " + dateFormat.format(new Date(randomTime))); } out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { DateWrapper[] dates = new DateWrapper[500]; try { BufferedReader in = new BufferedReader(new FileReader("temp.txt")); for (int i = 0; i < 500; i++) { String next = in.readLine(); String[] parts = next.split(" "); String num = parts[0]; String date = parts[1]; dates[i] = new DateWrapper(numFormat.parse(parts[0]).doubleValue(), dateFormat.parse(date)); } in.close(); } catch (Exception e) { e.printStackTrace(); } Arrays.sort(dates); for (int i = 0; i < 500; i++) { System.out.println(dates[i]); } } } } class DateWrapper implements Comparable { private double num; private Date date; public DateWrapper(double num, Date date) { this.num = num; this.date = date; } public int compareTo(Object o) { DateWrapper other = (DateWrapper)o; Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); calendar.setTime(other.getDate()); int dayOfWeek2 = calendar.get(Calendar.DAY_OF_WEEK); if (dayOfWeek < dayOfWeek2) { return -1; } else if (dayOfWeek > dayOfWeek2) { return 1; } else { return 0; } } public double getNum() { return num; } public Date getDate() { return date; } public String toString() { return date.toString(); } }