Java Exception Handling PDF
Document Details
Uploaded by Deleted User
2015
Liang
Tags
Summary
This document is a chapter from a Java programming textbook. It covers exception handling techniques and concepts in Java programming, with sections on various types of exceptions, including examples and ways to handle them. It also details file I/O using java functions and related classes.
Full Transcript
Chapter 12 Exception Handling and Text IO Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 1 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you h...
Chapter 12 Exception Handling and Text IO Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 1 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or terminate gracefully? This is the subject we will introduce in this chapter. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 2 Objectives To get an overview of exceptions and exception handling (§12.2). To explore the advantages of using exception handling (§12.2). To distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked vs. unchecked (§12.3). To declare exceptions in a method header (§12.4.1). To throw exceptions in a method (§12.4.2). To write a try-catch block to handle exceptions (§12.4.3). To explain how an exception is propagated (§12.4.3). To obtain information from an exception object (§12.4.4). To develop applications with exception handling (§12.4.5). To use the finally clause in a try-catch block (§12.5). To use exceptions only for unexpected errors (§12.6). Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 3 Objectives To rethrow exceptions in a catch block (§12.7). To create chained exceptions (§12.8). To define custom exception classes (§12.9). To discover file/directory properties, to delete and rename files/directories, and to create directories using the File class (§12.10). To write data to a file using the PrintWriter class (§12.11.1). To use try-with-resources to ensure that the resources are closed automatically (§12.11.2). To read data from a file using the Scanner class (§12.11.3). To understand how data is read using a Scanner (§12.11.4). Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 4 Exceptions Information includes: class name-line number-exception class Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 5 Exceptions Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 6 Exceptions Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 7 Exception-Handling Overview What will happen when user enter second number zero import java.util.Scanner; public class Quotient { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter two integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); System.out.println(number1 + " / " + number2 + " is " + (number1 / number2)); } } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 8 Exception-Handling Overview Fix it using an if statement import java.util.Scanner; public class QuotientWithIf { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter two integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); if (number2 != 0) System.out.println(number1 + " / " + number2 + " is " + (number1 / number2)); else System.out.println("Divisor cannot be zero "); } } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 9 Exception-Handling Overview Fix it With a method import java.util.Scanner; public class QuotientWithMethod { public static int quotient(int number1, int number2) { if (number2 == 0) { System.out.println("Divisor cannot be zero"); System.exit(1); } return number1 / number2; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter two integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); int result = quotient(number1, number2); System.out.println(number1 + " / " + number2 + " is " + result); } } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 10 Exception Advantages Now you see the advantages of using exception handling. It enables a method to throw an exception to its caller. Without this capability, a method must handle the exception or terminate the program. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 11 Handling InputMismatchException import java.util.*; public class InputMismatchExceptionDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean continueInput = true; do { try { System.out.print("Enter an integer: "); int number = input.nextInt(); // Display the result System.out.println("The number entered is " + number); continueInput = false; } catch (InputMismatchException ex) { System.out.println("Try again "Incorrect input"); input.nextLine(); // discard input } } while (continueInput); } } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 12 Exception Types ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object Throwable IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Many more classes Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 13 System Errors ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object Throwable IllegalArgumentException Many more classes System errors are thrown by LinkageError JVM and represented in the Error class. The Error class describes VirtualMachineError Error internal system errors. Such errors rarely occur. If one does, Many more classes there is little you can do beyond notifying the user and trying to terminate the program gracefully. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 14 Exceptions Exception describes errors caused by your ClassNotFoundException program and external ArithmeticException circumstances. These IOException errors can be caught and Exception NullPointerException handled by your RuntimeException program. IndexOutOfBoundsException Many more classes Object Throwable IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Many more classes Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 15 Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of- bounds array, and numeric errors. ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object Throwable IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Many more classes Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 16 Checked Exceptions vs. Unchecked Exceptions RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions in a try-catch block or declare it in the method header. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 17 Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 18 Unchecked Exceptions ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object Throwable IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Unchecked exception. Many more classes Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 19 Catching Exceptions try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; }... catch (ExceptionN exVar3) { handler for exceptionN; } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 20 Example: Declaring, Throwing, and Catching Exceptions Objective: This example demonstrates declaring, throwing, and catching exceptions by modifying the setRadius method in the Circle class defined in Chapter 8. The new setRadius method throws an exception if radius is negative. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 21 public class CircleWithException { private double radius; private static int numberOfObjects = 0; public CircleWithException() { this(1.0); } public CircleWithException(double newRadius) { setRadius(newRadius); numberOfObjects++; } public double getRadius() { return radius; } public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); } public static int getNumberOfObjects() { return numberOfObjects; } public double findArea() { return radius * radius * 3.14159; } } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 22 public class TestCircleWithException { public static void main(String[] args) { try { CircleWithException c1 = new CircleWithException(5); CircleWithException c2 = new CircleWithException(-5); CircleWithException c3 = new CircleWithException(0); } catch (IllegalArgumentException ex) { System.out.println(ex); } System.out.println("Number of objects created: " + CircleWithException.getNumberOfObjects()); } } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 23 The finally Clause try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 24 Using finally For each try-catch block there can be only one finally block. Case 1 :If an exception is thrown with a matching catch block then the finally block is executed after the catch block and program continues Case 2 : If an exception does not happen the finally block will be executed and program continues Case 3 : if an exception is thrown but not caught then the finally block will be executed after the try block , then program stops try{ //statment1 } Case 1:statment1-statment 2-statment3- statment4 catch(exception e){ //statment2 Case 2: statment1-statment3- } statment4 finally{ Case 3:statment1-statment3 //statment3 } 25 //statement 4 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 animation Trace a Program Execution Suppose no exceptions in the statements try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 26 animation Trace a Program Execution The final block is try { always executed statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 27 animation Trace a Program Execution Next statement in the try { method is executed statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 28 animation Trace a Program Execution try { Suppose an exception statement1; of type Exception1 is statement2; thrown in statement2 statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 29 animation Trace a Program Execution try { The exception is statement1; handled. statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 30 animation Trace a Program Execution try { The final block is statement1; always executed. statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 31 animation Trace a Program Execution try { The next statement in statement1; the method is now statement2; executed. statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 32 The general form of an exception-handling block try { class Exc2 { // block of code to monitor for errors public static void main(String args[]) { } int d, a; catch (ExceptionType1 exOb) { try { // monitor a block of code. // exception handler for d = 0; ExceptionType1 a = 42 / d; } System.out.println("This will not be printed."); catch (ExceptionType2 exOb) { } // exception handler for catch (ArithmeticException e) { ExceptionType2 System.out.println("Division by zero."); } } //... System.out.println("After catch statement."); finally { } // block of code to be executed before } try block ends } 33 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 The general form of an exception-handling block When an Exception is caught the program is transferred automatically to the appropriate catch block otherwise program stops The goal of most well-constructed catch clauses should be to resolve the exceptional condition and then continue on as if the error had never happened. Finally is always executed. 34 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 Three Basic Rules for Exception Handling Multiple catch Clauses Exception Propagation You can Catch an exception using a reference of its super class. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 35 1-Multiple catch Clauses ▪After one catch statement executes, the others are bypassed. ▪Exception subclasses must come before any of their superclasses, otherwise compile error void m(int i){ int [] x={1,4,0,2}; try{ int d=4/x[i]; } catch(ArrayIndexOutOfBoundsException e) {//} catch(ArithmeticException e) {//} } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 36 2-Exception Propagation If exception is not caught at its exact level , it propagates upwards towards the calling method Exception can be caught at a higher level public static void main (String [] args){ ExcepDemo3 n=new ExcepDemo3(); try{ n.m(3,0); } catch(ArithmeticException e){ //code to handle Exception} } } void m(int x,int y){ int z=x/y; } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 37 3-You can Catch an exception using a reference of its super clas Polymorphism try{ ……. } catch(Eexception e){ //code to handle Exception } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 38 Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b). void p1() { void p1() throws IOException { try { p2(); p2(); } catch (IOException ex) { }... } } (a) (b) Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 39 Specifying the Exceptions Thrown by a Method Every method must state the types of checked exceptions it might throw using the keyword throws. ▪ Method throwing checked exception is mandatory to declare it in method signature ▪ Method throwing unchecked exception is optional to declare it in method signature The calling method for a method that declares to throw a checked exception should surround the calling with try-catch or declare itself as throws, public void myMethod() throws IOException {…. } public void myMethod() throws IOException, OtherException {…. } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 40 Example : Handling The Exceptions from method Integer.parseInt Class Integer public static int parseInt (String s) throws NumberFormatException Parses the string argument as a signed decimal integer..….. Throws: NumberFormatException.regetni elbasrap a niatnoc ton seod gnirts eht fi - Unchecked Exception Optional try-catch 41 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 Creating Object of scanner to read data from a file public Scanner (File source) throws FileNotFoundException Constructs a new Scanner.elif deificeps eht morf dennacs seulav secudorp taht Parameters : source dennacs eb ot elif A - Throws : FileNotFoundExceptiondnuof ton si ecruos fi - Mandatory try-catch public static void m1 (){ checked File data=new File("Data.db"); Exception try{ Scanner scan =new Scanner(data); public static void m1 () throws FileNotFoundException } { catch(FileNotFoundException e) File data=new File("Data.db"); {//code to handle Exception} Scanner scan =new Scanner(data); } } } 42 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 Example public class Test { public static void main(String[] args) { int a=div(5,0); System.out.println("Result = "+a); } static int div(int x,int y){ int z; z=x/y; return z; } } What is the output? Exception in thread "main" java.lang.ArithmeticException: / by zero at Test.div(Test.java:8) at Test.main(Test.java:3) Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 43 Example: Problem Solution 1 public class Test { public static void main(String[] args) { try { int a = div(5, 0); System.out.println("Result = " + a); } catch (Exception ex) { System.out.println(ex); } } static int div(int x, int y) { int z; z = x / y; return z; } } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 44 Example: Problem Solution 2 public class Test { public static void main(String[] args) { try { int a = div(5, 0); System.out.println("Result = " + a); } catch (Exception ex) { System.out.println(ex); } } static int div(int x, int y) throws Exception{ int z; if(y==0)throw new Exception("DIVISION BY ZERO"); z = x / y; return z; } } If you write the method throws Exception, you must catch the exception in method call (write try-catch) Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 45 Throwing Exceptions Example public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 46 Throwing Exceptions Example class Student class Student { { private double GPA; private double GPA; public void setGPA(double GPA) public void setGPA(double GPA) throws Exception { { if(GPA>4) if(GPA>4) throw new Exception(); throw new IllegalArgumentException(); this.GPA=GPA; this.GPA=GPA; } } } } You can throw checked or unchecked exception using keyword throw Method that throws checked exceptions is mandatory to declare in its signature using keyword throws 47 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 Why Study Exception?? Handling Unchecked Exceptions Although not mandatory, handling these exceptions will make your program reliable, robust and error prone. Handling checked Exceptions a lot of methods in the Java API throws checked Exceptions , especially – methods that reads from file. – Methods that connect your program to a remote P.C. – Methods that connect your program to a database (Connection and querying) You must handle these exceptions to use these methods 48 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 Declaring your own exceptions You can define new exceptions ( checked or unchecked) by subclassing other Exceptions class myException extends RuntimException import java.io.IOException { class myException extends I0Exception Unchecked { Exception checked } Exception } Example class Student{ private int GPA; class GPAException extends public void setGPA(int GPA){ RuntimeException if(GPA>4) { throw new GPAException(); this.GPA=GPA; } }} 49 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 Custom Exception Class Circle Example The setRadius method throws an exception if the radius is negative. Suppose you wish to pass the radius to the handler, you have to create a custom exception class. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 50 public class InvalidRadiusException extends Exception { private double radius; public InvalidRadiusException(double radius) { super("Invalid radius " + radius); this.radius = radius; } public double getRadius() { return radius; } } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 51 class CircleWithCustomException { private double radius; private static int numberOfObjects = 0; public CircleWithCustomException() throws InvalidRadiusException { this(1.0); } public CircleWithCustomException(double newRadius) throws InvalidRadiusException { setRadius(newRadius); numberOfObjects++; } public double getRadius() { return radius; } public void setRadius(double newRadius) throws InvalidRadiusException { if (newRadius >= 0) radius = newRadius; else throw new InvalidRadiusException(newRadius); } public static int getNumberOfObjects() { return numberOfObjects; } public double findArea() { return radius * radius * 3.14159; } } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 52 public class TestCircleWithCustomException { public static void main(String[] args) { try { new CircleWithCustomException(5); new CircleWithCustomException(-5); new CircleWithCustomException(0); } catch (InvalidRadiusException ex) { System.out.println(ex); } System.out.println("Number of objects created: " + CircleWithException.getNumberOfObjects()); } } Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 53 JAVA I/O Processing 54 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 The File Class The File class is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion. The filename is a string. The File class is a wrapper class for the file name and its directory path. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 55 Obtaining file properties and manipulating file Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 56 The File Class To operate on a file, we must first create a File object (from java.io.File). Opens the file sample.dat File inFile = new File(“sample.dat”); in the current directory. File inFile = new File Opens the file test.dat in (“C:/SamplePrograms/test.dat”); the directory C:\SamplePrograms using the generic file separator / and providing the full pathname. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 Some File Methods To see if inFile is if ( inFile.exists( ) ) { associated to a real file correctly. if ( inFile.isFile() ) { To see if inFile is associated to a file or not. If false, it is a directory. File directory = new List the name of all files File("C:/JavaPrograms/Ch12"); in the directory C:\JavaProjects\Ch12 String filename[] = directory.list(); for (int i = 0; i < filename.length; i++) { System.out.println(filename[i]); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 Chapter 12 - 58 Text I/O A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. The objects contain the methods for reading/writing data from/to a file. This section introduces how to read/write strings and numeric values from/to a text file using the Scanner and PrintWriter classes. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 59 Reading Data Using Scanner java.util.Scanner +Scanner(source: File) Creates a Scanner object to read data from the specified file. +Scanner(source: String) Creates a Scanner object to read data from the specified string. +close() Closes this scanner. +hasNext(): boolean Returns true if this scanner has another token in its input. +next(): String Returns next token as a string. +nextByte(): byte Returns next token as a byte. +nextShort(): short Returns next token as a short. +nextInt(): int Returns next token as an int. +nextLong(): long Returns next token as a long. +nextFloat(): float Returns next token as a float. +nextDouble(): double Returns next token as a double. +useDelimiter(pattern: String): Sets this scanner’s delimiting pattern. Scanner ReadData Run Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 60 Class Scanner To read a file, create a File object and pass it as a parameter when constructing a Scanner. File f = new File("numbers.txt"); Scanner input = new Scanner(f); http://docs.oracle.com/javase/7/docs/api/java/util/Sca Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 61 Example: Reading Data using Class Scanner Numbers.txt 308.2 14.9 7.4 2.8 3.9 4.7 -15.4 2.8 Write a program that reads the first 5 values from this file and prints them along with their sum. Its output: number = 308.2 number = 14.9 number = 7.4 number = 2.8 number = 3.9 Sum = 337.19999999999993 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. © Pearson Education Limited 2015 62 // Displays the first 5 numbers in the given file, // and displays their sum at the end. import java.io.*; // for File, FileNotFoundException import java.util.*; public class Echo { public static void main(String[] args)throws FileNotFoundException { Scanner input = new Scanner(new File("numbers.txt")); double sum = 0.0; for (int i = 1; i