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

user input exceptions and reading and writing text files
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

User Input, Exceptions, and Reading and Writing Text Files

15-121 Fall 2020 Margaret Reid-Miller

slide-2
SLIDE 2

Today

  • Homework3: is available
  • due Monday September 21th 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

slide-3
SLIDE 3

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? _______ ____ _____; type name

Fall 2020 15-121 (Reid-Miller) 3

Writing classes

private

slide-4
SLIDE 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 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

fields

slide-5
SLIDE 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

slide-6
SLIDE 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

slide-7
SLIDE 7

Methods are usually are either public

  • r 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

slide-8
SLIDE 8

Text Input

slide-9
SLIDE 9
  • 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

Reading User Input

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

slide-10
SLIDE 10

Fall 2020 15-121 (Reid-Miller) 10

First, we need to create a Scanner

  • bject using the new operator.

Scanner console = new Scanner(System.in);

  • console is a variable that refers to the Scanner
  • bject. It can have any variable name.
  • Scanner() is the constructor that sets up the
  • bject.
  • 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.

slide-11
SLIDE 11

Fall 2020 15-121 (Reid-Miller) 11

Scanner Methods

String nextLine()

  • Reads and returns the next line of input.

String next()

  • Reads and returns the next token (e.g., one word,
  • ne 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. no static

slide-12
SLIDE 12

Fall 2020 15-121 (Reid-Miller) 12

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();

import java.util.Scanner;

slide-13
SLIDE 13

Fall 2020 15-121 (Reid-Miller) 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?

slide-14
SLIDE 14

Handling Exceptions

slide-15
SLIDE 15

Fall 2020 15-121 (Reid-Miller) 15

Exceptions are unusual or erroneous situations from which a program may

  • r 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.

slide-16
SLIDE 16

Fall 2020 15-121 (Reid-Miller) 16

There are many types of exceptions.

  • When do we get the following exceptions?

StringIndexOutOfBoundsException ArrayIndexOutOfBoundsException NullPointerException ArithmeticException FileNotFoundException

slide-17
SLIDE 17

Fall 2020 15-121 (Reid-Miller) 18

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.

slide-18
SLIDE 18

Fall 2020 15-121 (Reid-Miller) 19

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

  • f 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

slide-19
SLIDE 19

Fall 2020 15-121 (Reid-Miller) 20

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.

slide-20
SLIDE 20

Fall 2020 15-121 (Reid-Miller) 22

Example: Catching an exception

String fileName = null; do { System.out.print(“Enter file name: “) String fileName = console.nextLine(fileName); try { Scanner in = new Scanner(new File(fileName)); } catch (FileNotFoundException e) { System.out.println(“Error: File not found”); fileName = null; } } while (fileName == null);

e is a reference to the exception object. The catch block can call methods on e to find out more details about the exception. The try block encloses code that might raise an exception.

slide-21
SLIDE 21

Fall 2020 15-121 (Reid-Miller) 23

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.

slide-22
SLIDE 22

Fall 2020 15-121 (Reid-Miller) 25

Example: Throwing an exception

public void writeFile(String fileName) throws IOException { ... PrintWriter out = new PrintWriter(fileName);

  • ut.print(“Lab 3 results: ”);
  • ut.println(result);
  • ut.close();

}

The method can throw this exception to the method that called it. If there is a problem with opening the file for writing, PrintWriter will throw an IOException.

slide-23
SLIDE 23

Fall 2020 15-121 (Reid-Miller) 26

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.

slide-24
SLIDE 24

Fall 2020 15-121 (Reid-Miller) 27

Any exception that inherits from RuntimeException is unchecked,

  • therwise 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.

slide-25
SLIDE 25

Fall 2020 15-121 (Reid-Miller) 28

Exception Hierarchy

By looking at the Java API, you can determine whether an exception inherits from the RuntimeException class. If not, the method must catch or specify it throws the exception.

Exception RuntimeException NoSuchElementException IOException FileNotFoundException InputMismatchException (unchecked) (checked) ArithmeticException

slide-26
SLIDE 26

Reading a Text File

slide-27
SLIDE 27

Fall 2020 15-121 (Reid-Miller) 32

Reading a Text File

  • A Scanner object can be connected to many input

sources: console, string, file, network url.

  • To read a text file, we create a Scanner object

passing a File object instead of System.in as the argument:

// Read from data.txt file Scanner fileInput = new Scanner(new File("data.txt"));

Creates a Java File

  • bject (does not create a

file on your disk)

slide-28
SLIDE 28

Fall 2020 15-121 (Reid-Miller) 33

Example: Data in a file with a header line

File data.txt contains: 6 22 35 14 18 9 32

First line is the number of values that follow in the file.

slide-29
SLIDE 29

Fall 2020 15-121 (Reid-Miller) 34

E.g., Read a file with a count header

import java.util.Scanner; import java.io.*; // for File public class DataAnalyzer { public static void main(String[] args) throws FileNotFoundException { Scanner fileInput = new Scanner(new File(“data.txt”)); If Scanner throws an exception, then main will throw it and crash. If there is a problem with opening the file for reading, Scanner will throw an exception.

slide-30
SLIDE 30

Fall 2020 15-121 (Reid-Miller) 35

E.g., Read a file with a count header (cont'd)

int numValues = fileInput.nextInt(); int[] values = new int[numValues]; for (int i = 0; i < numValues; i++) { data[i] = fileInput.nextInt(); … } close(fileInput); }

Releases system resources

slide-31
SLIDE 31

Fall 2020 15-121 (Reid-Miller) 36

Scanner has methods to check for more input.

boolean hasNextLine()

Returns true if there is another line of data in its input.

boolean hasNext()

Returns true if there is another token in its input.

boolean hasNextInt()

Returns true if there is another token in its input and that token can be read as an int.

boolean hasNextDouble()

Returns true if the there is another token in its input and that token can be read as a double.

  • These methods do not consume input; They just say

whether and what kind of input is waiting.

slide-32
SLIDE 32

Fall 2020 15-121 (Reid-Miller) 37

E.g., Read a file until there is no more data.

// Count the words in essay.txt public static void main(String[] args) throws IOException { Scanner input = new Scanner (new File("essay.txt")); int count = 0; while (input.hasNext()) { String word = input.next(); count++; } close(input); System.out.println("Number of words is " + count); }

slide-33
SLIDE 33

Fall 2020 15-121 (Reid-Miller) 39

Common file reading exceptions

FileNotFoundException: Could not find the file: The file should be in the folder from which you invoke the program. NoSuchElementException: Attempted to read passed the end of the file. (E.g., A loop reads 8 integers when there are only 7 integers.) InputMismatchException: Attempted to read one type of token, but the next token was a different type. (E.g., Used nextInt when the next token contained letters.)

slide-34
SLIDE 34

Writing a File

slide-35
SLIDE 35

Fall 2020 15-121 (Reid-Miller) 41

Writing to a text file is similar to writing to System.out (console)

public static void main(String[] args) throws IOException { … PrintWriter outfile = new PrintWriter( “results.txt”);

  • utfile.println(“Water sample analysis“);
  • utfile.print(“Number of samples”);

  • utfile.close();

Must close output file to ensure all the data are written to the file. name of file to create (overwrites) Class requires import java.io.*;

slide-36
SLIDE 36

Example using multiple Scanners

slide-37
SLIDE 37

Fall 2020 15-121 (Reid-Miller) 43

Example: Line-Based Processing

  • A file contains hours worked:

103 Dave 3.2 5.6 4.0 2.5 238 Sue 4.9 8.5 211 Joe 3.1 2.5 4.1 1.5 2.3 1.4

  • Report the total hours worked:

Dave (id# 103) worked 15.3 hours Sue (id# 238) worked 13.4 hours Joe (id# 211) worked 14.9 hours

  • We need to process individual tokens, but the line breaks

tell us when one person is done. Strategy:

  • Read one line at a time.
  • Break each line into tokens.

Cannot process using

  • nly tokens because

hasNextDouble will include next person's id

slide-38
SLIDE 38

Fall 2020 15-121 (Reid-Miller) 44

Step 1: Read one line at a time

public class HoursProcessor { public static void main(String[] args) throws IOException { Scanner fileInput = new Scanner( new File("hoursWorked.txt")); // Read each line of the file while (fileInput.hasNextLine()) { String line = fileInput.nextLine(); processLine(line); } close(fileInput); }

slide-39
SLIDE 39

Fall 2020 15-121 (Reid-Miller) 45

Step 2: Break each line into tokens

public static void processLine(String text) { Scanner textInput = new Scanner(text); int id = textInput.nextInt(); String name = textInput.next(); double sum = 0.0; while (textInput.hasNextDouble()) { sum += textInput.nextDouble(); } System.out.println(name + " (id# " + id + ") worked " + sum + " hours"); }

Can read from a String, too.

103 Dave 3.2 5.6 4.0 2.5