1 / 37

ISE 582: Web Technology for Industrial Engineering

ISE 582: Web Technology for Industrial Engineering. University of Southern California DJE Dept of Industrial and Systems Engineering. Lecture 6. JAVA Cup 5: Data Structures. Handouts. Lecture 6 slides READ Winston & Narasimhan : Chapters 27-31, 33 (pp 149-194, 201-203). JAVA Cup 5.

heaton
Download Presentation

ISE 582: Web Technology for Industrial Engineering

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. ISE 582: Web Technology for Industrial Engineering University of Southern California DJE Dept of Industrial and Systems Engineering Lecture 6 JAVA Cup 5: Data Structures

  2. Handouts • Lecture 6 slides • READ Winston & Narasimhan : • Chapters 27-31, 33 (pp 149-194, 201-203) Web Technology for IE

  3. JAVA Cup 5 • File Access • Input file streams • Output file streams • Arrays and Vectors • How to create and access arrays • Expandable vectors • Characters and Strings Web Technology for IE

  4. File Input Streams • Reading files one-byte-at-a-time • Taking bigger bites • Java’s input-output package • Traditional string handling • Updating to tokens: number / words Web Technology for IE

  5. File input streams • A stream is a sequence of values. • To read bytes from a file: • FileInputStreamstream = newFileInputStream(“input.data”) • FileInputStreamstream = newFileInputStream(“~username/public_html/ise582/input.data”); • When you are done, it is good to: • stream.close() • Reads ONE BYTE AT A TIME… Web Technology for IE

  6. To take bigger bites than bytes • To read characters from your file: • InputStreamReaderreader = newInputStreamReader(stream); • To read lines from your file: • BufferedReaderbuffer = newBufferedReader(reader); • buffer.readLine() stream reader buffer Web Technology for IE

  7. Input-output package • Notify JAVA that you want to work with input or output streams: • import java.io.FileInputStream • import java.io.* • In the event of error • use try-catch statements • throw an exception, throwsIOException Web Technology for IE

  8. Traditional Approach Example import java.io.*; public class Demonstrate { public static void main(String argv[]) throwsIOException { FileInputStreamstream = new FileInputStream(“input.data”); InputStreamReaderreader = new InputStreamReader(stream); BufferedReaderbuffer = new BufferedReader(reader); String line; while ((line=buffer.readLine())!=null && !line.equals(“”)) { System.out.println(“Line read: “ + line); } stream.close(); return; }} Web Technology for IE

  9. String Methods • line.trim() • removes white space • line.indexOf(“ “) • index of first occurrence, starts from 0 • line.substring(2) • returns rest of line after index 2 • line.substring(0,1) • Integer.parseInt(“4”) • converts string to integer Web Technology for IE

  10. Example Continued line = line.trim(); int nextSpace = line.indexOf(" "); int x = Integer.parseInt(line.substring(0,nextSpace)); line = line.substring(nextSpace).trim(); nextSpace=line.indexOf(" "); int y = Integer.parseInt(line.substring(0,nextSpace)); line = line.substring(nextSpace).trim(); int z = Integer.parseInt(line); System.out.println("Numbers read: " + x + ", " + y + ", " + z); Web Technology for IE

  11. The Token Approach • The stream tokenizer: • StreamTokenizertokens = newStreamTokenizer(reader); • Do away with the BufferedReader • Divides character sequences into tokens, delimited by white space • Token Methods: • tokens.nextToken() • assigns value to nval, tokens.nval • always a double, if need recasting: (int) tokens.nval • end of token string indicated by TT_EOF: tokens.TT_EOF Web Technology for IE

  12. Token Example import java.io.*; public class Demonstrate { public static void main (String argv[]) throws IOException { FileInputStream stream = new FileInputStream("input.data"); InputStreamReader reader = new InputStreamReader(stream); StreamTokenizertokens = new StreamTokenizer(reader); while (tokens.nextToken()!= tokens.TT_EOF) { int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; Movie m = new Movie(x,y,z); System.out.println("Rating: " + m.rating()); } stream.close(); }} Web Technology for IE

  13. Words vs. Numbers • If the token is a number • nextToken returns a TT_NUMBER instance • the number is assigned to nval • If the token is a word • nextToken returns a TT_WORD instance • the number is assigned to sval Web Technology for IE

  14. Word / Number Example int next=0; while ((next=tokens.nextToken())!= tokens.TT_EOF) { switch (next) { casetokens.TT_WORD: break; casetokens.TT_NUMBER: int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; Movie m = new Movie(x,y,z); System.out.println("Rating: " + m.rating()); break; } } Web Technology for IE

  15. Arrays and Vectors • Creating / assigning values to arrays • Passing arrays to methods • Command-line arguments • Creating vectors • Vector methods • Vectors as targets • Using vector iterators Web Technology for IE

  16. Creating Arrays • Creating an array • <elt_type><array_name>[] = new<elt_type>[ <size>]; • int durations [] = new int [4]; • What you can do with an array • call / assign an elt: <array_name> [<index>] • find its length: <array_name>.length • Arrays of class instances • <Class><array_name>[] = new<Class>[<size>]; • Movie movies [] = new Movie [4]; Web Technology for IE

  17. Instance Array Elements • Field-selection operator still works • movies[3].script = 6 • Checking to see if element is assigned • movies[2] == null • Using instance as target for method • movies[1].rating() Web Technology for IE

  18. Mixing Creation and Elt Insertion public class Demonstrate { public static void main (String argv[]) { Movie movies[] = { new Movie(5,6,3), new Movie(8,7,7), new Movie(7,2,2), new Movie(7,5,5)}; int sum = 0; for (int counter=0; counter < movies.length; ++counter) { sum += movies[counter].rating(); } System.out.print("The average rating of the " + movies.length); System.out.println(" movies is " + sum / movies.length); } } Web Technology for IE

  19. Arrays and Memory • Arrays are reference type variables • Integer arrays contain a length variable and 4 bytes of memory per instance • Class instance arrays contain a length variable and several bytes for the address of each instance Web Technology for IE

  20. Higher Dimension Arrays • You can easily define arrays of higher dimension • double 2DArray[] [] = new double[2][100]; Web Technology for IE

  21. Passing an Array to a Method • To designate that a parameter is array • public static Movie[] readData(Movie movies []) throws IOExc.. • public static Movie[] readData(Movie[] movies) throws IOExc.. • E.g.: put file-reads into Auxiliary Class • Some ways to define readData: • Create array, pass array address to method, return address • Create array, pass array address to method, return nothing • Create array variable, pass filename to method, return array Web Technology for IE

  22. Command-Line Arguments • The main methods has one parameter • an array of Strings, argv[] • argv.length is # command-line arguments Web Technology for IE

  23. Example public class Command { public static void main(String argv[]) { Movie m = new Movie(Integer.parseInt(argv[0]), Integer.parseInt(argv[1]), Integer.parseInt(argv[2])); System.out.println("The rating is " + m.rating()); } } Web Technology for IE

  24. Vectors • Vectors vs. Arrays • variable in length • insertions can occur at any point • elements can only be class instances • Provided by Java’s utility package • import java.util.* • Vector v = new Vector(); Web Technology for IE

  25. Vector Methods • Insertions and deletions • v.addElement(m) … adds to back end of vector • v.insertElementAt(m,0) … adds to front of vector • v.removeElementAt(0) … removes first element • v.setElementAt(m,4) … replaces element • Access to elements • v.firstElement() • v.lastElement() • v.elementAt(2) • Size of Vector • v.size() Web Technology for IE

  26. A Little Quiz • Which methods do you need to represent FIFO queues? • Which methods do you need to represent LIFO queues (stacks)? Web Technology for IE

  27. Vectors as Targets • All vector elements are instances of the Object class • All vector methods work with instances of the Object class • You can work with an element of the vector class by casting the element: • ( (Movie)(v.firstElement()) ).rating() Web Technology for IE

  28. Example import java.io.*; import java.util.*; public class Auxiliaries2 { public static Vector readData(String fileName) throws IOException { FileInputStream stream = new FileInputStream(fileName); InputStreamReader reader = new InputStreamReader(stream); StreamTokenizer tokens = new StreamTokenizer(reader); Vector v = new Vector(); while (tokens.nextToken() != tokens.TT_EOF) { int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; v.addElement(new Movie(x,y,z)); } stream.close(); return v; }} Web Technology for IE

  29. Iterators • An iterator maintains a pointer to a place on the parent vector • To create an iterator • Iterator i = v.iterator() • Some Iterator methods • i.next() … returns element, advances pointer • i.hasNext() Web Technology for IE

  30. Example import java.io.*; import java.util.*; public class Demonstrate { public static void main(String argv[]) throws IOException { Vector mainVector = Auxiliaries2.readData("input.data"); int size = mainVector.size(); for ( Iterator i = mainVector.iterator(); i.hasNext(); ) { System.out.println(( (Movie) i.next() ).rating()); } } } Web Technology for IE

  31. Working with Char & Strings • What you can do with Strings • Specifying delimiters in File-reads Web Technology for IE

  32. The String s • s.length() … compare this to arrays • + concatenates two strings • s.charAt(0) extracts first character • s.charAt(0)==‘M’ … note single quotes • switch(s) … use in switch statements • char c = s.charAt(0); • default character is ‘\u000’ Web Technology for IE

  33. Example (excerpt) while (tokens.nextToken() != tokens.TT_EOF) { String codeString = tokens.sval; tokens.nextToken(); int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; switch (codeString.charAt(0)) { case 'M': v.addElement(new Movie(x,y,z)); break; case 'S': v.addElement(new Symphony(x,y,z)); break; } } Web Technology for IE

  34. Specifying Delimiters • To advise the tokens tokenizer to use double quotation marks to delimit strings: • tokens.quoteChar((int) ‘”’) • To tell the tokenizer to recognize carriage returns: • tokens.eolIsSignificant(true); Web Technology for IE

  35. Example (excerpt) tokens.quoteChar((int) '"'); tokens.eolIsSignificant(true); Vector v = new Vector(); while (tokens.nextToken() != tokens.TT_EOF) { String nameString = tokens.sval; tokens.nextToken(); int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; Movie m = new Movie(x,y,z); m.title = nameString; if (tokens.nextToken() == tokens.TT_EOL) {} else { m.poster = tokens.sval; tokens.nextToken(); } v.addElement(m); } Web Technology for IE

  36. Working with O/p File Streams • To connect to output file • FileOutputStreamstream = newFileOutputStream(“output.data”); • To write more than 1-byte-at-a-time • PrintWriterwriter = new PrintWriter(stream); • It’s good to flush out buffered characters • writer.flush() • Close the file • stream.close() Web Technology for IE

  37. Example (part) import java.io.*; import java.util.*; public class Demonstrate { public static void main(String argv[]) throws IOException { FileOutputStreamstream = new FileOutputStream("output.data"); PrintWriterwriter = new PrintWriter(stream); Vector mainVector = Auxiliaries4.readData("input3.data"); int size = mainVector.size(); for (Iterator i = mainVector.iterator(); i.hasNext();) { Movie m = (Movie) i.next(); m.writeToFile(writer); writer.println(m.rating()); } writer.flush(); stream.close(); System.out.println("File written"); }} Web Technology for IE

More Related