70 likes | 80 Views
Foundations of Software Design Fall 2002 Marti Hearst. Lab 7 discussion topics: Casting, File I/O, Enumeration, and Stacks John Fritch, Kaichi Sung, Leah Zagreus. Type Casting. Assigning primitive data when it would result in loss of precision (a) System.out.println(1/2);
E N D
Foundations of Software DesignFall 2002Marti Hearst Lab 7 discussion topics: Casting, File I/O, Enumeration, and Stacks John Fritch, Kaichi Sung, Leah Zagreus
Type Casting • Assigning primitive data when it would result in loss of precision (a) System.out.println(1/2); (b) System.out.println((float)1/2); • Assigning an object to a subclass type FishoneFish=newFish("one fish"); stack.push(oneFish); FishtwoFish=(Fish)stack.pop(); System.out.println(twoFish.getColor()); Adapted from Brian Overland, Java in Plain English 2nd ed.
Type Casting • Used a lot in Java because nearly all data structures store generic Object types. • Stack • Vector • HashTable • etc.
Enumeration • A convenient way to iterate through the elements in a data structure • Must use type casting Fishcharlie=newFish("pink"); Fishfreddy=newFish("yellow"); Vectorv=newVector(); v.add(charlie); v.add(freddy); Enumeratione=v.elements(); while(e.hasMoreElements()){ Fishf=(Fish)e.nextElement(); System.out.println(f.getColor()); }
File I/O • Java uses streams for input and output • Input streams – reading data from files, user input, keyboard • Output streams – writing data to files, screen, printer • Basic outline for File I/O: • Open the file for reading or writing • Read or write the data • Close the file Adapted from Oliver Mason, Programming for Corpus Linguistics
Reading from a File • Import the IO classes import java.io.*; • To open a file for reading (1 char at a time) FileReader fr = new FileReader("myFile.txt"); • To open a file for reading (more functionality) BufferedReaderbr=newBufferedReader(newFileReader("myFile.txt")); • Requires try-catch – Eclipse will help Adapted from Oliver Mason, Programming for Corpus Linguistics
StringTokenizer • Break up a string into “tokens” separated by “delimiters” • Words (what is the delimiter?) • Or any substrings, separated by the delimiter of your choosing StringTokenizerst=newStringTokenizer("this is a test"); while(st.hasMoreTokens()) System.out.println(st.nextToken()); Adapted from Oliver Mason, Programming for Corpus Linguistics