user input exceptions and reading and writing text files
play

User Input, Exceptions, and Reading and Writing Text Files 15-121 - PowerPoint PPT Presentation

User Input, Exceptions, and Reading and Writing Text Files 15-121 Fall 2020 Margaret Reid-Miller Today Homework3: is available due Monday September 21 th at 11:55pm From last time: Encapsulation Reading User Input Handling


  1. User Input, Exceptions, and Reading and Writing Text Files 15-121 Fall 2020 Margaret Reid-Miller

  2. Today • Homework3: is available • due Monday September 21 th at 11:55pm • From last time: Encapsulation • Reading User Input • Handling exceptions • Reading a text file • Writing to a text file Fall 2020 15-121 (Reid-Miller) 2

  3. Writing classes What 3 things may appear inside a class? fields constructors methods What should I determine first? the fields Think: "What does my object need to remember?" How do you declare a field? _______ ____ _____; private type name Fall 2020 15-121 (Reid-Miller) 3

  4. Inside a constructor or non-static method, what variables does it have access to? 1. local variables declared inside the method 2. parameters 3. fields fields In a static method, we cannot access _______. (or anything that isn't static without creating an object first) What are Java's visibility modifiers? Fall 2020 15-121 (Reid-Miller) 4

  5. Classes (and their parts) have visibility modifiers : • public : accessible to everyone • protected : inside package, inside class, inside subclass • package-private (default, no modifier used): inside package, inside class • private : accessible only within the class Fall 2020 15-121 (Reid-Miller) 5

  6. Data fields are usually private Data (fields): • Whatever the object needs to store • Available to clients via “getter” and “setter” methods. • Are private to encapsulate the object data from clients and to ensure class invariants . Fall 2020 15-121 (Reid-Miller) 6

  7. Methods are usually are either public or private. public: Only those methods that are part of the interface (the methods the client can call). • They can’t assume the client will supply correct arguments. • These methods must ensure that the pre- and post- conditions are met and post-conditions maintain the class invariants . private: “ helper” methods inside the class • Since clients cannot call these methods, and the server can ensure its calls meet the pre-conditions, these methods need not check the pre-conditions. Fall 2020 15-121 (Reid-Miller) 7

  8. Text Input

  9. Reading User Input https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html • The Scanner class has methods for reading user input values while the program is running . • The Scanner class is in the java.util package. • Related classes are grouped into packages. • Most of the classes we use are in the java.lang package, which is always available. • To use classes in other packages use an import declaration before the class header : import java.util.Scanner; Fall 2020 15-121 (Reid-Miller) 9

  10. First, we need to create a Scanner object using the new operator. Scanner console = new Scanner(System.in); • console is a variable that refers to the Scanner object. It can have any variable name. • Scanner() is the constructor that sets up the object. • System.in is an object in the System class that refers to the standard input stream which, by default, is the keyboard. Often, we use print instead of println when we prompt the user what to enter as input. Fall 2020 15-121 (Reid-Miller) 10

  11. Scanner Methods no static String nextLine() • Reads and returns the next line of input. String next() • Reads and returns the next token (e.g., one word, one number). double nextDouble() • Reads and returns the next token as a double value. int nextInt() • Reads and returns the next token as an int value. These methods pause until the user has entered some data and pressed the return key. Fall 2020 15-121 (Reid-Miller) 11

  12. import java.util.Scanner; Scanner Example Scanner console = new Scanner(System.in); System.out.print( "What is the model & make of your vehicle? "); String vehicleMake = console.nextLine(); System.out.print( "How many miles did you drive? "); int miles = console.nextInt(); System.out.print( "How many gallons of fuel did you use? "); double gallons = console.nextDouble(); Fall 2020 15-121 (Reid-Miller) 12

  13. Scanner Caveats • nextInt , nextDouble , and next read one token at a time. The scanner's position moves to after the token. Tokens are delimited by whitespace (space, tab, newline • characters) Several tokens can be on the same input line or on separate • lines. • nextLine reads from its current position to the end line and moves to the next line. It may return a string of no characters if it is called after calling one of the above methods and it is at the end of the line; you need to call nextLine twice! • What happens if the user does not enter an integer when we use nextInt ? Fall 2020 15-121 (Reid-Miller) 13

  14. Handling Exceptions

  15. Fall 2020 Exceptions are unusual or erroneous situations from which a program may or may not be able to recover. • Often the problem is out of the control of the program, such as bad user input. • When a exception occurs the Java runtime system creates an Exception object that holds information about the problem. • An exception will cause a program to halt unless it is caught and handled with special code. 15-121 (Reid-Miller) 15

  16. Fall 2020 There are many types of exceptions. • When do we get the following exceptions? StringIndexOutOfBoundsException ArrayIndexOutOfBoundsException NullPointerException ArithmeticException FileNotFoundException 15-121 (Reid-Miller) 16

  17. Fall 2020 Handling Exceptions • A robust program handles bad input gracefully, such as asking the user to reenter the name of a file when the file is not found. • When an exception occurs the method can either • catch the exception and execute some code to “handle” it, or • throw the exception back to the method that called it so that the calling method may handle the exception. 15-121 (Reid-Miller) 18

  18. Fall 2020 Unchecked vs Checked Exceptions Unchecked - Generally indicates error that the programmer should have prevented. If you do not handle the exception, your program crashes. • Examples: ArrayIndexOutOfBoundsException NullPointerException • The compiler doesn't check for these exceptions. Checked - Generally indicates invalid conditions outside of the control of program (or programmer). The compiler checks if these might occur and requires that your method either catches or throws these exceptions. • Examples: FileNotFoundException ClassNotFoundException 15-121 (Reid-Miller) 19

  19. Fall 2020 Scanner might throw an exception Scanner console = new Scanner(System.in); System.out.print(“Enter file name: “) String fileName = console.nextLine(); Scanner fileIn = new Scanner(new File(fileName)); If the user mistypes the file name, Scanner throws a FileNotFoundExcpetion . 15-121 (Reid-Miller) 20

  20. Fall 2020 Example: Catching an exception The try block encloses String fileName = null; code that might raise do { an exception. System.out.print(“Enter file name: “) String fileName = console.nextLine(fileName); try { Scanner in = new Scanner(new File(fileName)); e is a reference to the } exception object. catch (FileNotFoundException e) { System.out.println(“Error: File not found”); fileName = null; The catch block can call methods on e to } find out more details } while (fileName == null); about the exception. 15-121 (Reid-Miller) 22

  21. Fall 2020 Using a try-catch statement • Put code that might throw an exception in a try block. • Put code that handles the exception in a catch block immediately following the try block. • When the code inside the try block is executed: • If there are no exceptions , execution skips the catch block and continues after the catch block. • If there is an exception , execution goes immediately to the catch block and then continues after the catch block. 15-121 (Reid-Miller) 23

  22. Fall 2020 Example: Throwing an exception public void writeFile(String fileName) throws IOException { ... PrintWriter out = new PrintWriter(fileName); out.print(“Lab 3 results: ”); out.println(result); If there is a problem with opening out.close(); the file for writing, PrintWriter will throw an IOException . } The method can throw this exception to the method that called it. 15-121 (Reid-Miller) 25

  23. Fall 2020 Using throws vs try-catch • If the method throws an exception, its calling method similarly can either catch or throw the exception. • If the exception gets thrown all the way back to the main method and the main method doesn't catch it, the runtime system stops the program and prints the exception with a “call stack trace.” • Deciding if and which method should handle an exception is a software design decision, as is defining new exceptions for special types of errors. 15-121 (Reid-Miller) 26

  24. Fall 2020 Any exception that inherits from RuntimeException is unchecked, otherwise it is checked • Checked (checked at compile time) • The compiler requires that the method either specifies it throws the exception or it handles the exception in a try-catch statement. • Unchecked (not checked at compile time) • A robust method should prevent the exception or may use a try-catch statement to handle it. 15-121 (Reid-Miller) 27

Recommend


More recommend