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

User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

  • Upload
    others

  • View
    9

  • Download
    0

Embed Size (px)

Citation preview

Page 1: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

User Input, Exceptions, and Reading and Writing Text Files

15-121 Fall 2020Margaret Reid-Miller

Page 2: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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

Page 3: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

What 3 things may appear inside a class?fieldsconstructorsmethods

What should I determine first?the fieldsThink: "What does my object need to remember?"

How do you declare a field?_______ ____ _____;

type nameFall 2020 15-121 (Reid-Miller) 3

Writing classes

private

Page 4: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Inside a constructor or non-static method, what variables does it have access to?1. local variables declared inside the method2. parameters3. 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

Page 5: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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

Page 6: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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

Page 7: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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

Page 8: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Text Input

Page 9: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

• 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 Inputhttps://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

Page 10: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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

Page 11: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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,

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.

no static

Page 12: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 12

Scanner ExampleScanner 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;

Page 13: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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?

Page 14: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Handling Exceptions

Page 15: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 15

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.

Page 16: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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

Page 17: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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.

Page 18: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 19

Unchecked vs Checked ExceptionsUnchecked - Generally indicates error that the programmer should have prevented. If you do not handle the exception, your program crashes.

• Examples: ArrayIndexOutOfBoundsExceptionNullPointerException

• 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: FileNotFoundExceptionClassNotFoundException

Page 19: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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, Scannerthrows a FileNotFoundExcpetion.

Page 20: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 22

Example: Catching an exceptionString 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.

Page 21: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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.

Page 22: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 25

Example: Throwing an exception

public void writeFile(String fileName) throws IOException {

...PrintWriter out = new PrintWriter(fileName);out.print(“Lab 3 results: ”);out.println(result);out.close();

}

The method can throw this exception to the method that called it.

If there is a problem with opening the file for writing, PrintWriterwill throw an IOException.

Page 23: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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.

Page 24: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 27

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.

Page 25: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 28

Exception HierarchyBy 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

Page 26: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Reading a Text File

Page 27: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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 fileScanner fileInput =

new Scanner(new File("data.txt"));

Creates a Java Fileobject (does not create a file on your disk)

Page 28: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 33

Example: Data in a file with a header line

File data.txt contains:

622351418932

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

Page 29: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 34

E.g., Read a file with a count headerimport 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.

Page 30: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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

Page 31: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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.

Page 32: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 37

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

// Count the words in essay.txtpublic 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);}

Page 33: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 39

Common file reading exceptionsFileNotFoundException:

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.)

Page 34: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Writing a File

Page 35: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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”);outfile.println(“Water sample analysis“);outfile.print(“Number of samples”);…outfile.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.*;

Page 36: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Example using multiple Scanners

Page 37: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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.5238 Sue 4.9 8.5211 Joe 3.1 2.5 4.1 1.5 2.3 1.4

• Report the total hours worked:Dave (id# 103) worked 15.3 hoursSue (id# 238) worked 13.4 hoursJoe (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 only tokens because hasNextDouble will include next person's id

Page 38: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

Fall 2020 15-121 (Reid-Miller) 44

Step 1: Read one line at a timepublic class HoursProcessor {

public static void main(String[] args) throws IOException {

Scanner fileInput = new Scanner( new File("hoursWorked.txt"));

// Read each line of the filewhile (fileInput.hasNextLine()) {

String line = fileInput.nextLine();processLine(line);

}close(fileInput);

}

Page 39: User Input, Exceptions, and Reading and Writing Text Filesnew exceptions for special types of errors. Fall 2020 15-121 (Reid-Miller) 27 Any exception that inherits from RuntimeExceptionis

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