750 likes | 762 Views
Learn advanced array concepts, like managing multi-dimensional arrays and upgrading to ArrayLists and Vectors. Dive into Java time handling with Date class and Calendar functions for efficient date and day representations in your code.
E N D
Advanced Review • Time classes • Date Classes • File input/output • Packages
Multiple dimensions • No reason cant create 4,5,6 dimension arrays • Gets hard to manage • Better idea: • Think about another way of representing the data • Often creating an object is a better approach
Arrays further • Need to explicitly copy contents of arrays when resizing arrays with temp one • Better solution: • ArrayList • Vector • Full object versions of arrays • Capacity can grow over time • Useful methods bundles with them
code • Create a new class with a main called VectorTest • Create a vector • Put in some stuff • Print them out • Replace something in the middle • Print it out • Clear the vector • Print it out
Default values • Should be aware if you forget to set values • Might mess up your logic • Think of multiplying a bunch of numbers and not setting one of them… • Compiler/IDE will let you know if you forgot to set values (warning)
Time • Next lets discuss how time is handled in Java • Java.util.Date is the way java represents a point in time • It is measured in milliseconds • Time = 0 what does that mean?
Date • Time 0 = first millisecond in 1970 • Historical reasons for this • long is the type it uses • Range to +9,223,372,036,854,775,807 • Don’t memorize that • Lets look at the API • What is a deprecated method ?? • Example: getDay() ??
Why Date • Why are we wrapping the time long number? • "I'll see you on 996,321,998,346." doesn’t really work • Also allows you to easily order and compare different points in time….meaningfully
Change over time (no pun) • Nothing you program should be set in stone • Sometimes your design changes • Need to go back and change your code • Deprecated methods are those which have been replaced…but left in place so your old stuff shouldn’t crash if you try to recompile with latest jdk
Back to time • System.currentTimeMillis() • Returns the current time on the system • As a Date Object
Ideas • Although would like to represent a point in time, usually time is associated with other measurements • Month • Year
The GregorianCalendar Class • The Date class doesn't measure months, weekdays, etc. • That's the job of a calendar • A calendar assigns a name to a point in time • Many calendars in use: • Gregorian • Contemporary: Hebrew, Arabic, Chinese • Historical: French Revolutionary, Mayan
Next step • Lets design a new class to represent a day • Today is Tuesday Day today = new Day(); Today.add(1); //should give us Wednesday
Goal of Day Class • Answer questions such as • How many days are there between now and the end of the year? • What day is 100 days from now? • How many days till my birthday (I’ve always wanted a _____________)
Designing the class • Lets have a method • daysFrom it computes number of days between two days: int n = today.daysFrom(birthday); • addDays computes a day that is some days away from a given day: Day later = today.addDays(999); • Mathematical relationship: d.addDays(n).daysFrom(d) == n d1.addDays(d2.daysFrom(d1)) == d2
Constructor Date(int year, int month, int date) • Will need the following methods: • getYear • getMonth • getDate
Implementation • Straightforward which member will need: private int year private int month private int date • addDays/daysBetween tedious to implement • April, June, September, November have 30 days • February has 28 days, except in leap years it has 29 days • All other months have 31 days • Leap years are divisible by 4, except after 1582, years divisible by 100 but not 400 are not leap years • There is no year 0; year 1 is preceded by year -1 • In the switchover to the Gregorian calendar, ten days were dropped: October 15, 1582 is preceded by October 4
Day Code public Day(int aYear, int aMonth, int aDate) { year = aYear; month = aMonth; date = aDate; } private int year; private int month; private int date; private static final int[] DAYS_PER_MONTH = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private static final int GREGORIAN_START_YEAR = 1582; private static final int GREGORIAN_START_MONTH = 10; private static final int GREGORIAN_START_DAY = 15; private static final int JULIAN_END_DAY = 4; private static final int JANUARY = 1; private static final int FEBRUARY = 2; private static final int DECEMBER = 12;
Day Code private Day nextDay() 112: { 113: int y = year; 114: int m = month; 115: int d = date; 116: 117: if (y == GREGORIAN_START_YEAR 118: && m == GREGORIAN_START_MONTH 119: && d == JULIAN_END_DAY) 120: d = GREGORIAN_START_DAY; 121: else if (d < daysPerMonth(y, m)) 122: d++; 123: else 124: { 125: d = 1; 126: m++; 127: if (m > DECEMBER) 128: { 129: m = JANUARY; 130: y++; 131: if (y == 0) y++; 132: } 133: } 134: return new Day(y, m, d); 135: }
private static int daysPerMonth(int y, int m) { int days = DAYS_PER_MONTH[m - 1]; if (m == FEBRUARY && isLeapYear(y)) days++; return days; } private static boolean isLeapYear(int y) { if (y % 4 != 0) return false; if (y < GREGORIAN_START_YEAR) return true; return (y % 100 != 0) || (y % 400 == 0); }
Tester 01: public class DayTester 02: { 03: public static void main(String[] args) 04: { 05: Day today = new Day(2001, 2, 3);//February 3, 2001 06: Day later = today.addDays(999); 07: System.out.println(later.getYear() 08: + "-" + later.getMonth() 09: + "-" + later.getDate()); 10: System.out.println(later.daysFrom(today));// Prints 999 11: } 12: }
Notice • Private helper methods • Notice all the work to increment a day
Another idea • This is for illustration, don’t need to code • For greater efficiency, we can use Julian day number • Used in astronomy • Number of days since Jan. 1, 4713 BCE • May 23, 1968 = Julian Day 2,440,000 • Greatly simplifies date arithmetic
Code public Day(int aYear, int aMonth, int aDate) { //notice we are calling a private //helper function julian = toJulian(aYear, aMonth, aDate); } //that’s all we need private int julian;
Helper function private static int toJulian(int year, int month, int date) { int jy = year; if (year < 0) jy++; int jm = month; if (month > 2) jm++; else{ jy--; jm += 13; } int jul = (int) (java.lang.Math.floor(365.25 * jy) + java.lang.Math.floor(30.6001 * jm) + date + 1720995.0); int IGREG = 15 + 31 * (10 + 12 * 1582); // Gregorian Calendar adopted Oct. 15, 1582 if (date + 31 * (month + 12 * year) >= IGREG) // Change over to Gregorian calendar { int ja = (int) (0.01 * jy); jul += 2 - ja + (int) (0.25 * ja); } return jul; }
Any other ideas? • So you see that using the class doesn’t change even though we totally changed how the inside works • Called encapsulation • So its easy to move up or down the calendar • Add subtract • Where would it cost us ??
Switch gears • Lets talk about how to use files • Your program starts in main, computes, then maybe prints out something before closing up • Would be great if can save results somewhere • Hey lets use files
File manipulations • Working with files • Reading files • Writing files
Please note • One of the great things about file manipulation on java is that it is the same on • Windows • Linux • Mac • If done right
File • Basic object is called File • File data = new File(“test.txt”); • It will look in the same directory the java file is sitting in for the test file • Calling: data.getAbsolutePath() • Will print out the local version of the full path to the file
Directories • If your File object is a directory • The list method returns an array of String file names, • listFiles returns an array of File objects
limitations • The File object has a limited number of useful methods • None which can actually write something to it • Need to use higher level class to work with file contents
Dealing with text • When dealing with text output/input can use • PrintWriter to write to a file
code • PrintWriter pw = new PrintWriter(new FileWriter(new File("Test.txt"))); • What is FileWriter ? • Lets pull up the API
Helper class to help make sure things are written efficiently • Don’t forget to close the file handle when done • And flush if using a buffered handle
Ok lets write some code • Main program • Will write a 3 line poem (yes you need to write one now) to a test.txt file • Notice how your have to add try catch to handle certain declared exceptions ??
Run code • Confirm that the file has been created • Now write another class to read the file
How would you adopt the reader to find something in the file ??
For each line read • Look for something • See String API for helper methods • Now write the code
Next up • Interfaces • Inheritance • Abstract Classes • Polymorphism • Generics
Two dimensions • You can also initialize the inner array as a separate call. • Doesn’t have to be congruous memory locations int [][]example = new int[5][]; for (int i=0;i<5;i++){ example[i] = new int[i+1]; }
Interface • An interface is a special class that defines the behavior of other classes • Example • How many mp3 players are on the market ?
Mp3 players • No matter what type of mp3 player you buy you expect certain behavior • Play • Forward(next song) • Rewind(last song) • Random • Think of your own
If I want to program a bunch of mp3 players and want to force all of them to have some minimum behavior I would encode that as an interface • Here is an example:
code public interface mp3player { public boolean play(); public boolean rewind(); public boolean forward(); public int getSongCount(); public boolean deleteAll(); }
analysis • Basically am defining ideas • Would add comments to each what they are supposed to be doing (expected behavior • Then any class which wants to be nice, would agree to behave this way
Code: IpodMP3 • Say we want to create a really cool mapple ipod player • Want to stick to the mp3 behavior public class Ipodmp3 implements mp3player { .. • This means that we need to define those methods for this specific class
Note • Can implement as many interfaces as you like • Will notice them in the api when you look at the standard libraries • Compiler will check and complain if you don’t implement all the methods you are promising in the interface you impliment • Nothing actually checks that you are doing the correct thing….that is up to the programmer