1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
1 Java intro Part 2. 2 Access control in Java classes Public members: accessible to any code that can access the class Private members: accessible only.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Applets & Applications CSC 171 FALL 2001 LECTURE 15.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Static Class Members Wrapper Classes Autoboxing Unboxing.
Chapter 3b Standard Input and Output Sample Development.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: IO *Standard Output *Formatting Decimal.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
1 Course Lectures Available on line:
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
CIS 270—Application Development II Chapter 13—Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
SOFTWARE TECHNOLOGY - I CONSTANTS VARIABLES DATA TYPES.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Department of Computer Engineering Using Objects Computer Programming for International Engineers.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
CPRG 215 Introduction to Object-Oriented Programming with Java Module 2- Using Java Built-in Classes Topic 2.4 Using Java Built-in Classes Produced by.
CSCI 1100/1202 January 23, Class Methods Some methods can be invoked through the class name, instead of through an object of the class These methods.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Wrapper Classes Use wrapper objects in Collections when you can’t use primitive types Primitive TypeWrapper Class byteByte shortShort intInteger longLong.
Java Programming. Objects  Java is an object-oriented programming language –use objects to define both the data type and the operations that can be applied.
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Objectives You should be able to describe: Interactive Keyboard Input
CS1101: Programming Methodology Recitation 7 – Exceptions
Introduction to Exceptions in Java
Interactive Standard Input/output
Objects, Classes, Program Constructs
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
Web Design & Development Lecture 7
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Tutorial Exceptions Handling.
Exception Handling Contents
Presentation transcript:

1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader class. l Preview: Catching Exceptions.

2 WRAPPER CLASSES l Java uses primitive types, such as int and char, for performance reasons. l However, there are times when a programmer needs to create an object representation for one of these primitive types. l Java provides a Wrapper class for each of the primitive types. All these classes are in the java.lang package: Primitive typeWrapper class booleanBoolean byteByte charCharacter shortShort intInteger longLong floatFloat doubleDouble

3 WRAPPER CLASSES (cont.) l Wrapper classes are used to provide constants and general methods for the primitive data types. l Converting strings into numbers l Each of the Wrapper classes Byte, Short, Integer, Long, Float, and Double has a method to convert a string representation of a number of the corresponding primitive type into its numeric format: Examples: int numStudents = Integer.parseInt(“500”) ; String inputLine ;... double studentGPA = Double.parseDouble( inputLine) ; Wrapper classParse method ByteparseByte(string) ShortparseShort(string) IntegerparseInt(string) LongparseLong(string) FloatparseFloat(string) DoubleparseDouble(string)

4 INTRODUCTION TO EXCEPTIONS l A program may have one or more of three types of errors: 1.Syntax errors or Compile-time errors. 2.Run-time or Execution-time errors. 3.Logic errors. l A Java exception is an object that describes a run- time error condition that has occurred in a piece of Java code or in the Java run-time System. l All Java exception classes are subclasses of the Throwable class. l Most exception classes are defined in the java.io and java.lang packages. other packages like: java.util, java.awt, java.net, java.text also define exception classes. l Catching and throwing an exception l A piece of Java code containing statements to handle an exception is said to catch the exception; otherwise it is said to throw that exception. l An exception that is not caught by any portion of a Java program will ultimately be caught by the default exception handler. The default exception handler displays a string describing the exception.

5 INTRODUCTION TO EXCEPTIONS (cont.) l A partial hierarchy of Java exceptions: Throwable ExceptionError... IOException RuntimeException... IllegalArgumentException NumberFormatException NullPointerException ArithmeticException...

6 INTRODUCTION TO EXCEPTIONS (cont.) l Checked and Unchecked exceptions Java exceptions are classified into two categories: checked exceptions and unchecked exceptions. Any exception that derives from the class Error or the class RuntimeException is an unchecked exception. All other exceptions are checked exceptions. l The Java rule for thrown exceptions: A METHOD MUST DECLARE ALL CHECKED EXCEPTIONS IT MAY THROW, OTHERWISE THE JAVA COMPILER WILL ISSUE AN ERROR MESSAGE. l The throws clause A method declares that it may throw an exception by a throws clause in the method header: access-specifier return-type method-name(parameter-list) throws exception-list {... }

7 INTRODUCTION TO EXCEPTIONS (cont.) Example: import java.io.* ; public static void main(String[ ] args) throws IOException {... } One or more statements that may throw an IOException that is not handled. Note: When a method declares that it throws an exception, then it may throw an exception of that class or any of its subclasses.

8 CONSOLE INPUT USING BufferedReader CLASS (cont.)  In Java I/O is handled by streams.  Input stream An input stream is an object that takes data from an input source and delivers that data to a program.  Output stream An output stream is an object that delivers data to an output destination.  In Java, console input is usually accomplished by reading from the input stream System.in of the class java.lang.System  System.in represents the standard input stream (i.e., the keyboard).  Unfortunately, System.in has no methods for reading characters, strings, or numbers. It has a read method to read a single byte at a time.[Java uses Unicode in which each character is two bytes]  To be able to read characters, strings, or numbers, System.in must be wrapped in other objects.

9 CONSOLE INPUT USING BufferedReader CLASS (cont.)  To turn System.in into a Reader object (i.e., an object that is capable of reading one character at a time), wrap System.in in an InputStreamReader object: InputStreamReader reader = new InputStreamReader(System.in) ; l To turn the object referenced by reader into an object with the ability to read entire lines at a time, wrap the object in a BufferedReader object: BufferedReader stdin = new BufferedReader(reader) ; l The steps of turning System.in into a BufferedReader object can be combined into a single statement: BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)) ; l Note: Both the BufferedReader class and the InputStreamReader class are defined in the java.io package.

10 CONSOLE INPUT USING BufferedReader CLASS (cont.) l The read( ) and readLine( ) methods The object to which stdin refers to contains a read( ) method that reads one character at a time, and returns its integer code in the range 0 to 65535: int read( ) throws IOException It also contains a readLine( ) method that reads one input line at a time, and returns it as a string: String readLine( ) throws IOException l Example: Reading a string import java.io.*; public class ReadString { public static void main(String[ ] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)) ; System.out.println(“Enter a line of text:”) ; String message = stdin.readLine( ) ; System.out.println(“You entered: ” + message ) ; }

11 CONSOLE INPUT USING BufferedReader CLASS (cont.) l Example: Reading a character char ch = (char) stdin.read( ) ; l Numeric input The Java library contains no classes to read numbers directly. One way of processing numeric input is to read it as a string using the readLine( ) method then convert it to its corresponding numeric value, using the parse method of an appropriate Wrapper class. l Example: String inputLine = stdin.readLine( ) ; int numStudents = Integer.parseInt(inputLine) ; double speed = Double.parseDouble(stdin.readLine( )) ; float height = Float.parseFloat(stdin.readLine( ).trim( )); Note: Each parse method can throw an unchecked NumberFormatException