Download presentation
Presentation is loading. Please wait.
Published byAlicia O’Connor’ Modified over 8 years ago
2
Copyright by Michael P.F. Fung 1 Introduction to Computing Using Java Exception Handling, Array & GUI
3
Copyright by Michael P.F. Fung 2 Exception ( 例外 / 情況 / 鑊 ) When running a program, there may be unexpected conditions or errors. E.g. –Network outage causing read error. –I/O Error (disk damage, disk full, etc.) It’s an art to handle the exceptions gracefully and correctly. –We won’t expect a blue screen during the course of running our programs!
4
Copyright by Michael P.F. Fung 3 Exceptionally Ugly
5
Copyright by Michael P.F. Fung 4 How to Deal With Exceptions Each exception is given a meaningful name, indicating the nature of it. We may define our own exceptions with our given names. Java has already defined some commonly used ones. –IOException, ArithmeticException, EOFException, etc. In any method, we may: –Raise exceptions (throw) –Detect exceptions (try) and Handle exceptions (catch) –Ignore exceptions (declare throws clause and propagate) Ignore means the method would suicide. The suicided method would become a killer (exception propagation).
6
Copyright by Michael P.F. Fung 5 IOException Objects Used when something gone wrong during general Input/Output operations. We may create (new) an IOException object from the class java.io.IOException. import java.io.*;...... new IOException();
7
Copyright by Michael P.F. Fung 6 Throwing IOException If we found/felt something wrong with I/O, we may create and throw an IOException object to the message sender. double tan(double angle) { // read a 4-figure table from file if (something_wrong_during_input) throw new IOException(); else... return answer; } … void main(…) { double value = tan(30); } Normal return
8
Copyright by Michael P.F. Fung 7 Throwing IOException If we found/felt something wrong with I/O, we may create and throw an IOException object to the message sender. double tan(double angle) { // read a 4-figure table from file if (something_wrong_during_input) throw new IOException(); else... return answer; } … void main(…) { double value = tan(30); } Abnormal return “throwing exception”
9
Copyright by Michael P.F. Fung 8 Throwing IOException If we found/felt something wrong with I/O, we may create and throw an IOException object to the message sender. double tan(double angle) { // read a 4-figure table from file if (something_wrong_during_input) throw new IOException(); else... return answer; } … void main(…) { double value = tan(30); } Rest skipped, method terminated
10
Copyright by Michael P.F. Fung 9 Still Something Wrong: Exception Declaration If we compile the above “program”, we will get a compilation error. We have to tell message senders: be ready to receive (possible) IOException’s: declaration. double tan(double angle) throws IOException { // read a 4-figure table from file if (something_wrong_during_input) throw new IOException(); else... return answer; }
11
Copyright by Michael P.F. Fung 10 Detecting Exceptions In the previous example, main() will be puzzled on receiving the IOException object from tan(). What should we do in the message sender? We have to define a try block in the message sender to detect exceptions. … void main(…) { double value = tan(30); }
12
Copyright by Michael P.F. Fung 11 Try Block From the signature of tan(), we know that sending this message is risky. double tan(double angle) throws IOException { … } … void main(…) { double value; try { value = tan(30); value = value * 3.14159; }
13
Copyright by Michael P.F. Fung 12 Try Block In case of receiving any exceptions from any statements in the try block, the rest (subsequent) statements in the try block will be skipped. double tan(double angle) throws IOException { … throw new IOException(); } … void main(…) { double value; try { value = tan(30); value = value * 3.14159; // wow wow, skipped }
14
Copyright by Michael P.F. Fung 13 Limited Liability Skipping the remaining statements in the try block means saving the method from dying! It avoids skipping the rest statements in the whole method body! i.e. rescuing the method. … void main(…) { double value; try { value = tan(30); value = value * 3.14159; // wow wow, skipped } double result = value + 19 * 97 - 2002; } Something is missing here… See next slide...
15
Copyright by Michael P.F. Fung 14 Twins: Detection and Handling In fact, try and catch are twins. Try is responsible for detection. Catch is responsible for identification and handling.
16
Copyright by Michael P.F. Fung 15 Handling Exceptions double tan(double angle) throws IOException { if (read_4_figure_table_error) throw new IOException(); … } … void main(…) { double value; try { value = tan(30); value = value * 3.14159; // wow wow, skipped … } catch (IOException io_exception_object_ref) { System.out.println(“Input Output Exception received!”); value = 3.14159; } // the program continues normally hereafter }
17
Copyright by Michael P.F. Fung 16 Handling Exceptions We catch certain type of exception by: catch (ExceptionType an_object_reference) { statements to remedy the condition; } // resume normal execution hereafter an_object_reference lets us access the fields/methods of the exception object. Thus further information may be passed from the exception thrower to the exception handler through the exception object.
18
Copyright by Michael P.F. Fung 17 Catching Several Kinds of Possible Exceptions double tan(double angle) throws IOException, ArithmeticException { if (read_4_figure_table_error) throw new IOException(); if (angle == 90) throw new ArithmeticException(); } … void main(…) { double value; try { value = tan(90); // tan 90 = infinity! value = value * 3.14159; // wow wow, skipped } catch (IOException io_exception_object_ref) { System.out.println(“Input Output Exception received!”); value = 3.14159; } catch (ArithmeticException arithmetic_exception_object_ref) { System.out.println(“Arithmetic Exception received!”); value = 0.0; } // the program continues normally hereafter }
19
Copyright by Michael P.F. Fung 18 Exception Propagation Unless encountering a try-catch block which handles the received exception, the exception will cause termination of the current method. In such case, the method re-throws (propagates) the same exception object to its message sender. The involved method should therefore declare that it may throw that exception in its method signature.
20
Copyright by Michael P.F. Fung 19 Exception Propagation double tan(double angle) throws IOException, ArithmeticException { if (read_4_figure_table_error) throw new IOException(); if (angle == 90) throw new ArithmeticException(); } … void main(…) throws ArithmeticException { double value; try { value = tan(90); // tan 90 = infinity! value = value * 3.14159; // wow wow, skipped } catch (IOException io_exception_object_ref) { System.out.println(“Input Output Exception received!”); System.out.println(“We have handled it gracefully!”); value = 3.14159; } // ArithmeticException is not caught // this method terminates and propagates the arithmetic exception object // on receiving ArithmeticException }
21
Copyright by Michael P.F. Fung 20 Top-Level Boss The Java Virtual Machine is the first message sender which sends a message to main(). It is thus the ultimate receiver of any un-handled exceptions. The exception propagation stops either on: –Reaching a try-catch block which handles the exception. –Or reaching the JVM and causing program termination.
22
Copyright by Michael P.F. Fung 21 Array Popular and important data structure –use an index to access variables of the same name (identifier) and type: i[0] = 5; i[654] = -378; How to do that? int[] i = new int[1000]; –OR( C++ style ) int i[] = new int[1000];
23
Copyright by Michael P.F. Fung 22 Declaration and Array Creation int[] i = new int[1000]; is equivalent to int[] i;// i is nothing yet i = new int[1000];// i keeps something
24
Copyright by Michael P.F. Fung 23 Another Form of Array Creation By enumerating its initial values: char[] vowels = {'a', 'e', 'i', 'o', 'u'}; Then vowels is an array of 5 char variables with vowels[0] 'a' vowels[1] 'e' vowels[2] 'i' vowels[3] 'o' vowels[4] 'u' Array index must be an integer: [0 to length – 1]. There are 5 char variables!
25
Copyright by Michael P.F. Fung 24 Syntax of Creating Arrays type[] array_name = new type[length]; type[] array_name = {value1, value2,...}; e.g. double[] GPA = new double[50]; String[] countryCode = new String[175]; String address[] = new String[30]; char[] vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}; type may be primitive type, class type or even an other array type.
26
Copyright by Michael P.F. Fung 25 Properties of Array A bounded (fixed length) and indexed collection of elements of the same type. Array length is fixed at the time of creation. Element access is done using an index [ ]. –vowels[0] to vowels[vowels.length – 1] –vowels[-8] ArrayIndexOutOfBoundsException To get the length (size) of an array: –vowels.length –NOT vowel.length() [confused with String]
27
Copyright by Michael P.F. Fung 26 Example: The Parameter in main() class TestArgs { public static void main(String[] args) { System.out.println("There are " + args.length + " arguments:"); int i; for (i = 0; i < args.length; i++) System.out.println( args[i] ); } C:\LetSee\> java TestArgs There are 0 arguments: C:\LetSee\> java TestArgs Apple Orange There are 2 arguments: Apple Orange
28
Copyright by Michael P.F. Fung 27 Example: The Parameter in main() A Java application program can receive some parameters at start-up. These start-up parameters are called command-line arguments. The main() method is the receiver of such arguments. Such arguments are stored in a String array created by the JVM. JVM sends a message to main() with such an array.
29
Copyright by Michael P.F. Fung 28 Array of Object References int[] i;// a null integer array reference i = new int[100];// create a new integer array i[5] = 87;// let i refer to the array // initially, i[0] = … = i[99] = 0 Octopus[] deck;// a null Octopus array reference deck = new Octopus[10]; // initially, deck[0] = … = null deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); Creating a new array Creating members
30
Copyright by Michael P.F. Fung 29 Array Itself is Also a Reference Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); deck[ ] (reference) ?
31
Copyright by Michael P.F. Fung 30 Array Itself is Also a Reference Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); deck[ ] (reference) deck[2] (reference) deck[1] (reference) deck[0] (reference) ? ? ?
32
Copyright by Michael P.F. Fung 31 Array Itself is Also a Reference Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); deck[ ] (reference) Octopus (class) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) ? ?
33
Copyright by Michael P.F. Fung 32 Array Itself is Also a Reference Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); deck[ ] (reference) Octopus (class) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) ?
34
Copyright by Michael P.F. Fung 33 Array Itself is Also a Reference Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); deck[ ] (reference) Octopus (object) Octopus (class) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) Class type array
35
Copyright by Michael P.F. Fung 34 Array Itself is Also a Reference int[] i; i = new int[3]; i[0] = 7; i[1] = i[0]; i[2] = 9; i[ ] (reference) i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 Primitive type array Class type array
36
Copyright by Michael P.F. Fung 35 Assignment of the Whole Array int[] i = new int[3]; int[] j; j = i; // object reference copying j[2] = 9; // i[2] = 9 i[1] = 7; // j[2] = 7 j[0] = 7; // i[0] = 7 i[ ] (reference) i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 j[ ] (reference) They refer to the same array!
37
Copyright by Michael P.F. Fung 36 Assignment of the Whole Array int[] i = new int[3]; int[] j; j = new int[5]; i[ ] (reference) i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 j[ ] (reference) OR, Create another one! j[4] (int) 0 j[3] (int) 0 j[2] (int) 0 j[1] (int) 0 j[0] (int) 0
38
Copyright by Michael P.F. Fung 37 Assignment of the Whole Array int[] i = new int[3]; int[] j; j = new int[5]; j = i; i[ ] (reference) i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 j[ ] (reference) Remember to Keep It Well! j[4] (int) 0 j[3] (int) 0 j[2] (int) 0 j[1] (int) 0 j[0] (int) 0
39
Copyright by Michael P.F. Fung 38 New Concept: Primitive Type Array Argument Passing class Student { public static void studyHard(double[] newGPAs) { newGPAs[0] = 4.0; newGPAs[1] = 4.0; } public static void main(String[] args) { double[] GPAs = new double[2]; GPAs[0] = 1.0; GPAs[1] = 1.5; Student.studyHard(GPAs); System.out.println(GPAs[0]); System.out.println(GPAs[1]); } newGPAs (Reference) GPAs (Reference) Start here GPAs[1] 1.5 GPAs[0] 1.0 GPAs[1] 4.0 GPAs[0] 4.0 Copy array reference to formal parameter when sending message. Change to the formal parameter DOES NOT affect actual parameter!
40
Copyright by Michael P.F. Fung 39 New Concept: Object Type Array Argument Passing class CUHK { public static void fire(Employee[] victims) { for (int i = 0; i < victims.length; i++) victims[i].salary = 0; } public static void main(String[] args) { Employee[] TAs = new Employee[3]; TAs[0] = new Employee(1000); TAs[1] = new Employee(2000); TAs[2] = new Employee(5000); CUHK.fire(TAs); } class Employee { public int salary; public Employee(int initialSalary) { salary = initialSalary; } TAs[0] (reference) TAs[1] (reference) Start here TAs[2] (reference) TAs (reference) victims (reference) Employee (object) salary 1000 Employee (object) salary 2000 Employee (object) salary 5000
41
Copyright by Michael P.F. Fung 40 Table (2-Level Array) // There are 176 students, 8 assignments // record their marks in double double[][] mark = new double[176][8]; mark[6][0] = 99.34;// mark: 7th student, Asg1 mark[175][6] = 89.12;// mark: last student, Asg7 double[] singleStudent; singleStudent = mark[175];// refer to the singleStudent[6] = 45.67; // marks of the last one System.out.println(mark[175][6]);// would print 45.67 Elements of an array could be arrays. Array reference of array references. What’s the type? double double[]
42
Copyright by Michael P.F. Fung 41 Table Illustrated mark[ ][ ] (reference) mark[2] (reference) mark[1] (reference) mark[0] (reference) mark[2][3] (double) 9.45 mark[2][2] (double) 2.49 mark[2][1] (double) 3.43 mark[2][0] (double) 1.75 mark[1][3] (double) 8.48 mark[1][2] (double) 3.40 mark[1][1] (double) 6.13 mark[1][0] (double) 1.15 mark[0][3] (double) 9.11 mark[0][2] (double) 1.42 mark[0][1] (double) 5.43 mark[0][0] (double) 0.35 Array of Array of double
43
Copyright by Michael P.F. Fung 42 Duplicating an int Array int[] i = {7, 7, 9}; int[] j; j = new int[i.length]; for (int count = 0; count < i.length; count++) j[count] = i[count]; i[ ] (reference) i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 Copy the elements one-by-one
44
Copyright by Michael P.F. Fung 43 Duplicating an int Array int[] i = {7, 7, 9}; int[] j; j = new int[i.length]; for (int count = 0; count < i.length; count++) j[count] = i[count]; i[ ] (reference) i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 j[ ] (reference) Copy the elements one-by-one ?
45
Copyright by Michael P.F. Fung 44 Duplicating an int Array int[] i = {7, 7, 9}; int[] j; j = new int[i.length]; for (int count = 0; count < i.length; count++) j[count] = i[count]; i[ ] (reference) i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 j[ ] (reference) Copy the elements one-by-one j[2] (int) 0 j[1] (int) 0 j[0] (int) 0
46
Copyright by Michael P.F. Fung 45 Duplicating an int Array int[] i = {7, 7, 9}; int[] j; j = new int[i.length]; for (int count = 0; count < i.length; count++) j[count] = i[count]; i[ ] (reference) i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 j[ ] (reference) Copy the elements one-by-one j[2] (int) 9 j[1] (int) 7 j[0] (int) 7
47
Copyright by Michael P.F. Fung 46 Duplicating an Object Array deck[ ] (reference) Octopus (object) Octopus (class) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) Octopus[] deck;... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count];
48
Copyright by Michael P.F. Fung 47 Duplicating an Object Array deck[ ] (reference) Octopus (object) Octopus (class) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) Octopus[] deck;... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; newDeck[ ] (reference) ?
49
Copyright by Michael P.F. Fung 48 Duplicating an Object Array deck[ ] (reference) Octopus (object) Octopus (class) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) Octopus[] deck;... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; newDeck[ ] (reference) newDeck[2] (reference) newDeck[1] (reference) newDeck[0] (reference)
50
Copyright by Michael P.F. Fung 49 Duplicating an Object Array deck[ ] (reference) Octopus (object) Octopus (class) deck[2] (reference) deck[1] (reference) deck[0] (reference) Octopus (object) Octopus[] deck;... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; newDeck[ ] (reference) newDeck[2] (reference) newDeck[1] (reference) newDeck[0] (reference) Only the object references are copied!
51
Copyright by Michael P.F. Fung 50 7-Minute Break
52
Copyright by Michael P.F. Fung 51 Graphics User Interface(GUI) Graphical User Interface Basic Elements Event Driven Model Trigger and Callback
53
Copyright by Michael P.F. Fung 52 Command-line User Interface
54
Copyright by Michael P.F. Fung 53 Graphical User Interface
55
Copyright by Michael P.F. Fung 54 GUI – Computer Display Use of graphical representations –Windows –Icons –Buttons –… To convey the underlying concepts –An icon represents a file –A button represents certain function
56
Copyright by Michael P.F. Fung 55 GUI – User Input Use of various interactive input devices –Keyboard –Mouse –Touch screen –… To gather command and control from user –A mouse click opens a file –A mouse drag moves a window –Pressing means “OK”
57
Copyright by Michael P.F. Fung 56 GUI and OOP A window is an object. A button is an object. We create windows and buttons from classes. Such objects –store state of the component (field/property); –perform certain function (method); –generates events (event objects); –respond to user actions (callback method);
58
Copyright by Michael P.F. Fung 57 1) Store State Basic properties –Colour –Size –Visibility Dynamic states –On/off state of a button –Value of a text field
59
Copyright by Michael P.F. Fung 58 2) Perform Action Draw circles Display text Paint the window
60
Copyright by Michael P.F. Fung 59 3) Generate Event Detect if you clicked a button Detect if you dragged the mouse pointer Detect if you dragged the scrollbar
61
Copyright by Michael P.F. Fung 60 4) Handle Event On clicking the buttons, moving the mouse, dragging the mouse, … over a component, events are generated. On receiving an event, the corresponding callback method of a listener is invoked. The method may update the screen, update the state, perform some function, etc.
62
Copyright by Michael P.F. Fung 61 How to Do it Using Java? One of the provided packages java.awt (Abstract Windowing Toolkit) is readily used. There are plenty of component classes well-defined in the package. –Frame: basically a window –Button: a push button with a label –TextField…
63
Copyright by Michael P.F. Fung 62 Simple Example import java.awt.*; /* This is not the usual way we call up GUI * Normally, we should subclass (extends) some * GUI components in order to modify the behaviour */ class SimpleGUI { public static void main(String[] args) { Frame myWindow = new Frame(); myWindow.setTitle("Simple GUI"); myWindow.setSize(200, 100); myWindow.setVisible(true); }
64
Copyright by Michael P.F. Fung 63 Components List - Classes
65
Copyright by Michael P.F. Fung 64 How to Use the Components? Read the API Manual and Books! Check for the components you need Create (new) the components Set their properties –Basic properties and initial state –Relationship between the components –Action to be performed on event happening
66
Copyright by Michael P.F. Fung 65 Component - Basic Properties Colour: setBackground(Color) setForeground(Color)setBackgroundsetForeground Size: setSize(int, int)setSize Position: setLocation(int, int)setLocation State: setEnabled(boolean)setEnabled Font: setFont(Font)setFont Visibility: setVisible(boolean)setVisible …
67
Copyright by Michael P.F. Fung 66 Component - Relationship Sibling/sub-ordinary relationship window.add(button1); Relative position between the components Button1 and Button2 are contained/embedded in the Frame Button1 is on the left of Button2 on the same row
68
Copyright by Michael P.F. Fung 67 Component - Event Generation Events are automatically generated during interaction with the user. Events are normally happened in conjunction with certain component(s). If the involved component(s) do not listen to (pay attention to) that event, normally nothing would happen.
69
Copyright by Michael P.F. Fung 68 Component - Event Listening To listen to an event, we need a listener: Frame myWindow = new Frame(); /* Adapter is a kind of Listener */ WindowAdapter adapter = new WindowAdapter(); myWindow.addWindowListener(adapter); add*Listener() are methods of components. We register a listener to listen to certain kind of events, say MouseEvent. –e.g. MouseListener may be MouseAdapter objects.
70
Copyright by Michael P.F. Fung 69 Event Handling Button1 MouseEvent Generates MouseAdapter mouseClicked mouseEntered mousePressed … Event Dispatching Event Handler may: - Update the appearance of the button - Modify the state of the button - Perform programmer-defined action such as “Say Hello” User action MouseListener
71
Copyright by Michael P.F. Fung 70 Listener Example import java.awt.*; import java.awt.event.*; class ListenGUI { public static void main(String[] args) { Frame myWindow = new Frame(); myWindow.setTitle("Simple GUI"); myWindow.setSize(200, 100); myWindow.setVisible(true); myWindow.addWindowListener(new MyWindowAdapter()); } class MyWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.out.println(“Terminating the program!”); System.exit(1);// a message to ask the System to exit //... OR you may open other windows!!! } File ListenGUI.java
72
Copyright by Michael P.F. Fung 71 Handler (Callback) Method An adapter in fact normally listens to a set of related events. For each kind of event, a corresponding handler method is defined. On receiving a MouseEvent which indicates mouse button pressed, the mousePressed() method of the MouseAdapter object will be invoked.
73
Copyright by Michael P.F. Fung 72 Customizing the Handling Without customizing (overriding) the default handler methods provided in the adapter, nothing would happen. That’s why we extends the WindowAdapter, MouseAdapter… classes. By re-defining (overriding) their methods, we can achieve desired behaviour in event handling.
74
Copyright by Michael P.F. Fung 73 Examples NormalMouseAdapter NormalWindowAdapter NormalGUI ListenGUI ListenGUI2
75
Copyright by Michael P.F. Fung 74 What Kinds of Events? Examples: –WindowEvent needs WindowListener. WindowAdapter is a kind of WindowListener. –MouseEvent needs MouseListener. MouseAdapter is a kind of MouseListener. The events themselves are generated by some components under user interaction.
76
Copyright by Michael P.F. Fung 75 After-Life of main() When and how does a GUI program end? main() is the first method to be invoked. Normally, after main() finishes, the program ends. But this is not the case for GUI programs... Why? The underlying event dispatching loop of the system takes over the control.
77
Copyright by Michael P.F. Fung 76 Advanced Topics Using Swing/ AWT with NetBeans –Setting properties and layout –Creating call-back methods Inner Classes
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.