1 / 75

Advanced Review

Advanced Review. 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.

dorothym
Download Presentation

Advanced Review

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced Review

  2. Advanced Review • Time classes • Date Classes • File input/output • Packages

  3. 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

  4. 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

  5. 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

  6. 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)

  7. 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?

  8. 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() ??

  9. 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

  10. 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

  11. Back to time • System.currentTimeMillis() • Returns the current time on the system • As a Date Object

  12. Ideas • Although would like to represent a point in time, usually time is associated with other measurements • Month • Year

  13. 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

  14. Relationships

  15. 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

  16. 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 _____________)

  17. 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

  18. Constructor Date(int year, int month, int date) • Will need the following methods: • getYear • getMonth • getDate

  19. 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

  20. 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;

  21. 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: }

  22. 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); }

  23. 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: }

  24. Notice • Private helper methods • Notice all the work to increment a day

  25. 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

  26. 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;

  27. 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; }

  28. 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 ??

  29. 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 

  30. File manipulations • Working with files • Reading files • Writing files

  31. 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

  32. 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

  33. 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

  34. 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

  35. Dealing with text • When dealing with text output/input can use • PrintWriter to write to a file

  36. code • PrintWriter pw = new PrintWriter(new FileWriter(new File("Test.txt"))); • What is FileWriter ? • Lets pull up the API

  37. 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

  38. 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 ??

  39. Run code • Confirm that the file has been created • Now write another class to read the file

  40. How would you adopt the reader to find something in the file ??

  41. For each line read • Look for something • See String API for helper methods • Now write the code 

  42. Next up • Interfaces • Inheritance • Abstract Classes • Polymorphism • Generics

  43. 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]; }

  44. Interface • An interface is a special class that defines the behavior of other classes • Example • How many mp3 players are on the market ?

  45. 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

  46. 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:

  47. code public interface mp3player { public boolean play(); public boolean rewind(); public boolean forward(); public int getSongCount(); public boolean deleteAll(); }

  48. 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

  49. 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

  50. 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

More Related