1 / 23

Reading Interactive Data

Reading Interactive Data. We can use javax.swing package and JOptionPane class JOptionPane class has a method call showInputDialog that takes a string (as prompt) and allows the user to enter a string Eg: s1 = JOptionPane.showInputDialog("Enter an integer");

brendaking
Télécharger la présentation

Reading Interactive Data

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. Reading Interactive Data • We can use javax.swing package and JOptionPane class • JOptionPane class has a method call showInputDialog that takes a string (as prompt) and allows the user to enter a string • Eg: s1 = JOptionPane.showInputDialog("Enter an integer"); • S1 is a string that can now be used.

  2. Reading Interactive Data - an example import javax.swing.JOptionPane; public class Example1 { public static void main(String[] args) { String s1, s2; int n1, n2, max; // prompt for integers s1 = JOptionPane.showInputDialog("Enter an integer"); s2 = JOptionPane.showInputDialog("Enter another integer"); // convert these strings to integers n1 = Integer.parseInt(s1); n2 = Integer.parseInt(s2); // find the maximum max = Math.max(n1,n2); // print the message and the max value JOptionPane.showMessageDialog(null, "The biggest is " + max); System.exit(0); } }

  3. Disk Files • Advantages • Persistence: data in a file lasts longer than data on the monitor • Capacity: more information can be stored on a disk than displayed at one time on a monitor • Attributes • Contents (data) • A file name • Operations • Writing to a file (creating and storing data for the first time) • Deleting a file • Renaming a file • Overwriting a file • Obtaining contents of a file

  4. Modeling disk files • Java provides a predefined class to model disk files, called File • Constructor for the file class • Accepts the files name (a String reference) as the argument • Example: File f1 = new File(“myData.txt”); • IMPORTANT: • We have created a reference to a file object • This does not create a file on the disk • If this file is not on the disk, we cannot do anything with this object

  5. If the file is on the disk • The File object provides two methods that model some of the operations we listed earlier: • delete() File f = new File(“junk.txt”); f.delete(); • renameTo() File f1, f2; f1 = new File(“junk.txt”); f2 = new File(“garbage.txt”); f1.renameTo(f2); Download FileStuff.zip demo

  6. Writing output to disk • To create a new file, or overwrite an existing file, we need a pathway, or stream • Java has a predefined class to model this stream, FileOutputStream • The constructor for FileOutputStream uses a reference to a File object as its argument File f = new File(“stuff.txt”); FileOutputStream fstream = new fileOutputStream(f); • Opens the file so that it can receive data • Creates a new file if the file does not exist • However, it does not provide any convenient methods for output

  7. Using PrintStream methods for disk files • We want a PrintStream object to be associated with a disk file and not a monitor • The PrintStream constructor takes a reference to a FileOutputStream as its argument • The PrintStream object is associated with the FileOutPutStream • Using println() and print() methods on this PrintStream object means that output will go to the disk file File f = new File(“stuff.txt”); FileOutputStream fstream = new FileOutputStream(f); PrintStream target = new PrintStream(fstream); target.println(“This is a new disk file.”);

  8. Catching exceptions (first pass) • In Karel we had runtime errors that would halt program flow • Try to pick a beeper when none were there • To to move through a wall that was in the way • A similar type of problem may be trying to access a file that is unavailable • We will add the line throws Exception to the heading of the main() method of our program class public static void main(String args[]) throws Exception {

  9. Throwing exceptions and methods • Any method that can throw an exception must acknowledge it in the header with a throws clause • A throws clause consists of the keyword throws and a list of all Exceptions thrown in the method • Example public static void main(String args[]) throws Exception {

  10. Throwing Exceptions • To handle the unexpected, Java uses the throw statement throw reference • Reference is an object of a subclass of the class Exception • See the API and the Java Interlude on page ??? of the text • The throw statement usually takes the following form throw new Exception-class(String-argument) • This is called throwing an exception

  11. Handling the unexpected • By default the throws statement launches a chain of method terminations from the method that executes the throw to the main() method, terminating the program itself • Often the program can respond to the unexpected and recover, by catching the Exception • Breaking the cascade of method throwing along the invocation chain

  12. try … catch() { } • To catch an Exception, the statements containing invocations of Exception-throwing methods are surrounded by braces and preceded with the keyword try try { someObject.someMethod(); … } • Following is thekeyword catch and a declaration of an reference variable that will refer to the thrown Exception object in parentheses catch (Exception e) { statements } • Finally comes a group of statements surrounded by braces that will be executed when the Exception reaches this method

  13. Implementing a try…catch in file output • We could also implement the try…catch mechanism in the following way File f = new File("stuff.txt"); try { FileOutputStream fstream = new FileOutputStream(f); PrintStream target = new PrintStream(fstream); target.println("This is a new disk file."); } catch (FileNotFoundException e) { System.out.println("File not found."); } • We will not worry about the details of this implementation at this time

  14. Creating or Overwriting a File: Summary • Create a File object to represent the file • Create a FileOutputStream object to represent the pathway to the file (using the File reference as an argument) • Create a PrintStream object to provide a convenient output pathway to the file (using the FileOutputStream reference as an argument) • Use print() or println() methods of PrintStream as needed • Be sure to watch for exceptions appropriately

  15. Input from keyboard, file, or network connection • Sequence of steps similar to output • Construct an object that models some sort of input stream • FileInputStream • BufferedInputStream • Use the input stream object to construct an InputStreamReader object • Models stream of input as a stream of characters • Does not recognize boundaries between Strings in the input • Use the InputStreamReader object to construct a BufferedReader object • Provides method readLine() reads an entire line, creates a String object, and returns a reference to that object

  16. Input: the keyboard • Java provides a predefined BufferedInputStream object to represent a stream of input that comes from the keyboard, System.in • Unlike System.out, System.in cannot be used right away (different classes) • System.in must be used to construct an InputStreamReader object • Which is used as an argument to construct a BufferedReader object • Which can then be sent readLine() messages to read lines as Strings

  17. Getting a line from the keyboard InputStreamReader isr; BufferedReader keyBoard; String inputLine; isr = new InputStreamReader(System.in); keyBoard = new BufferedReader(isr); inputLine = keyBoard.readLine(); System.out.print(inputLine); System.out.println("s");

  18. Interactive Input/Output • A program that expects input from a keyboard, must provide that information to the user as it runs • A general form for interactive input and output: System.out.print(prompt goes here); string reference variable = keyboard.readLine() possibly compute something System.out.println(output string goes here);

  19. Input: Disk Files • Only slightly more involved that obtaining input from a keyboard • Instead of BufferedInputStream object (System.in), we need a FileInputStream object • Construct a FileInputStream object the same as constructing a FileOutputStream object File f = new File(“myData.txt”); FileInputStream fs = new FileInputStream(f); • Now we can use the FileInputStream object as we used System.in in getting data from the keyboard

  20. Getting a line from a disk file File f = new File(“myData.txt”); FileInputStream fs = new FileInputStream(f); InputStreamReader isr; BufferedReader input; isr = new InputStreamReader(fs); input = new BufferedReader(isr); String inputLine; inputLine = input.readLine(); System.out.println(inputLine);

  21. Network Computing • Network concepts • Computer network: group of computers that can directly exchange information with each other • Internet: a computer network of networks. Allows computers on one network to exchange information with another computer on a different network • THE Internet • Each computer has it’s own unique Internet address • Internet addresses on the Net are Strings • Information on the Net is organized into units called network resources (usually a file of some type) • Each resource is uniquely identified by its URL (Universal Resource Locator) • Form of URL: protocol://internet address/file name

  22. Network Input • Reading input from the World Wide Web is as simple as reading data from a disk file • Obtain an InputStream that models a stream of input from a Web site • Class URL provided by Java to model URLs • The constructor for the URL class takes a String argument URL u = new URL(“http://www.whitehouse.gov”); • It also provides a method, openStream, that takes no arguments, but returns an InputStream InputStream ins = u.openStream();

  23. openStream() • Does a lot of work behind the scenes • Sets up communication software on your machine • Contacts the remote machine • Waits for response • Sets up connection • Constructs an InputStream object to model the connection • Returns a reference to this object • We then construct a BufferedReader as we did for disk files and keyboards Download WHWWW.zip demo

More Related