Lecture 6 Arrays and Interfaces.

Slides:



Advertisements
Similar presentations
Written by: Dr. JJ Shepherd
Advertisements

CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
The Web Warrior Guide to Web Design Technologies
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Cosc 4755 Phone programming: GUI Concepts & Threads.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Pemrograman Dasar Arrays PTIIK - UB. Arrays  An array is a container object that holds a fixed number of values of a single type.  The length of an.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CSC1401 Classes - 1. Learning Goals Computing concepts Identifying objects and classes Declaring a class Declaring fields Default field values.
Concurrent Programming and Threads Threads Blocking a User Interface.
Introduction to Java Java Translation Program Structure
Programming in Java CSCI-2220 Object Oriented Programming.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Written by: Dr. JJ Shepherd
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Arrays Chapter 7.
CSC 205 Programming II Lecture 5 AWT - I.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Values vs. References Lecture 13.
EECE 310: Software Engineering
Event-driven programming
Logger, Assert and Invariants
Introduction To Repetition The for loop
Some Eclipse shortcuts
Android 11: The Calculator Assignment
Java Programming Language
Testing and Debugging.
Exceptions, Interfaces & Generics
Creating Objects & String Class
Java Programming: From Problem Analysis to Program Design,
Arrays in C.
Miscellaneous Topics #6: Polygons GUI Components and Event Handlers
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Object Oriented Programming
Lecture 18 Arrays and Pointer Arithmetic
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Object-Oriented Software Engineering
CS18000: Problem Solving and Object-Oriented Programming
Object Oriented Programming
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
slides created by Ethan Apter
Building Java Programs
Lecture 11 Objectives Learn what an exception is.
Object-Oriented Programming Using C++ Second Edition
Constructors, GUI’s(Using Swing) and ActionListner
Tonga Institute of Higher Education
Chapter 5 Processing Input with Applets
Suggested self-checks: Section 7.11 #1-11
Java SE 7 One and Multi Dimensional Arrays Module 6
CMSC 202 Exceptions 2nd Lecture.
Data Structures & Algorithms
Introduction to Object-Oriented Programming
Defining Classes and Methods
Building Java Programs
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Java Programming: From Problem Analysis to Program Design, 4e
ITEC220 GUI Lecture – Part 2 References
Week 7 - Monday CS 121.
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Lecture 6 Arrays and Interfaces

Objectives Learn to use arrays. Learn to implement interfaces. Default Arrays Array Initializers arraycopy Learn to implement interfaces. Discuss events. Introduce event listeners.

Arrays in Java In Java, arrays are objects. In addition to the usual C operations they also have methods and attributes. The are declared differently than in C. There are two ways to declare an array. An array can be declared to contain a default value. An array can be declared using an array initializer to contain values we specify. Creating an array in Java is a two step process. First we create a reference (pointer) to an array object that can contain the correct variable type. Next, we reserve memory for the array an associate it with the reference.

Declaring Default Arrays First we create the reference to the array. int[] x; Next we reserve the memory for the array and associate it with the reference. x = new int[12]; These can be combined into a single line. int[] x = new int[12]; The elements of the array will contain whatever is the default value of their type. for(int i = 0; i < 12; i++) System.out.printf("x[%d] = %d ", i, x[i]); This produces the following output x[0] = 0 x[1] = 0 x[2] = 0 x[3] = 0 ... The default value for an int is 0.

Array Initializer Declaring an array using an array initializer doesn’t require us to explicitly specify the number of items in the array. int[] y = {12, 8, 7, 3, 4, 0, -1, 5}; One of the attributes of an array is its size. System.out.printf(”y has length %d.", y.length); If you use an index that is out of bounds an exception will be thrown. If you do not catch it, your program will crash.

Passing Arrays to Functions The following is a function that accepts an array as one of its parameters. static void arrayModifier(int[] p){ for (int i = 0; i < p.length; i++) p[i] = i; } The function is static so that we can call it without creating an object. Notice the parameter type is int[] (an array of ints). Recall that an array is an object, so modifying its elements will change the actual parameter. Notice the we can use the length attribute to avoid running off the end of the array.

Passing Arrays Functions Here is an example of some code that uses our function. int[] x = new int[12]; System.out.println("Before function call."); for(int i = 0; i < 12; i++) System.out.printf("x[%d] = %d ", i, x[i]); System.out.printf("%n"); arrayModifier(x); System.out.println("After function call,");

Passing Arrays to Functions Here is the output. Before function call. x[0] = 0 x[1] = 0 x[2] = 0 x[3] = 0 x[4] = 0 ... After function call, x[0] = 0 x[1] = 1 x[2] = 2 x[3] = 3 x[4] = 4 ... The function did modify the array entries. Notice this does not violate the call by value. The array that was passed as a parameter (the address in memory) did not change – the contents of the memory is what changed.

Array Operations Indexing arrays works just as it did in C. There is a System method, arraycopy, that can be used to copy an array. arraycopy(Object src, int srcPos, Object dest, int destPos, int length) src – the source array. srcPos – the position to begin copying from. dest – the destination array. destPos – the position to begin copying to. length – the number of elements to copy.

Array Copy This code produces the output int[] a = {0, 1, 2, 3, 4, 5, 6}; int[] b = {1, 1, 1, 1, 1, 1, 1} System.arraycopy(a, 3, b, 1, 4); for(int i = 0; i < 7; i++) System.out.printf("b[%d] = %d ", i, b[i]); This code produces the output b[0] = 1 b[1] = 3 b[2] = 4 b[3] = 5 b[4] = 6 b[5] = 1 b[6] = 1 Four elements of array a, starting at index 3, were copied into array b, starting at index 1.

Array Demo The following is a program that demonstrates the array handling we have gone over. public class ArrayDemo { // A function that modifies an array static void arrayModifier(int[] p){ for (int i = 0; i < p.length; i++) p[i] = i; } public static void main(String[] args){ // default array declaration int[] x = new int[12]; System.out.println("Before function call."); for(int i = 0; i < 12; i++) System.out.printf("x[%d] = %d ", i, x[i]); System.out.printf("%n");

Array Demo // passing the array to a function arrayModifier(x); System.out.println("After function call,"); for(int i = 0; i < 12; i++) System.out.printf("x[%d] = %d ", i, x[i]); System.out.printf("%n"); // an array of characters char[] y; y = new char[5]; for(int i = 0; i < 5; i++) System.out.printf("y[%d] = %c ", i, y[i]); // array initializer int[] z = {12, 8, 7, 3, 4, 0, -1, 5, 14, 6}; // the length of the array System.out.printf("%nThe length of z is %d.%n", z.length);

Array Demo // copying an array int[] a = {0, 1, 2, 3, 4, 5, 6}; int[] b = {1, 1, 1, 1, 1, 1, 1}; System.out.println("Before the copy."); for(int i = 0; i < 7; i++) System.out.printf("b[%d] = %d ", i, b[i]); System.out.printf("%n"); System.arraycopy(a, 3, b, 1, 4); System.out.println("After the copy."); }

Interfaces One object oriented tool that Java provides is the ability to define an interface. An interface is a list of methods that a class must support. An example consider designing a car – cars have a fairly standard user interface (steering wheel, gas, brake, etc.) Different cars may implement the interface differently. What happens when you step on the gas? As long as a car supports the common interface we can drive the car. The methods of a class that supports an interface are like the controls on the car.

Interface Example Suppose we want to create an interface that could be used for bank accounts. There are several ways to interact with accounts but in our example we could do the following. Add money to the account (creditAccount) Withdraw money from the account (debitAccount) Print the balance (printBalance) If we want to support both credit card and checking accounts we should handle these actions differently. Debiting a credit card means you own more money. Debiting a checking account means you have less money.

Interface Example Here is an interface definition. interface Account{ void debitAccount(double x); void creditAccount(double x); void printBalance(); } If this is stored in a separate .java file then the interface would need to be public. The interface lists methods that classes implementing it must possess. These classes could have additional methods not listed in the interface. The methods in the interface do not have bodies. They can be implemented in different ways in different classes.

Implementing an Interface All the different account classes must declare that they implement the interface. Then the compiler will ensure that they have the required methods. If a class doesn’t have the necessarily methods that will be a syntax error. The methods can be implemented any way that is appropriate for that class. The classes can have other methods than the ones specified in the interface. Classes can also implement multiple interfaces.

Example Class The following is a class to implement a checking account. Notice that a checking account holds assets. class Checking implements Account { double assets; String name; Checking(double amount, String name){ assets = amount; this.name = name; }

Example Class The methods that implement the interface must be public. public void debitAccount(double amount){ assets -= amount; } public void creditAccount(double amount){ assets += amount; public void printBalance(){ System.out.printf("You have $%.2f in %s", assets, name); The methods that implement the interface must be public.

Example Class A different class is used to implement credit card accounts. Notice that a credit account holds debts. class Credit implements Account { double debt; String name; Credit(double amount, String name){ debt = amount; this.name = name; }

Example Class public void debitAccount(double amount){ debt += amount; } public void creditAccount(double amount){ debt -= amount; public void printBalance(){ System.out.printf("You owe $%.2f to %s", debt, name);

Using Interfaced Classes Because these classes support the same interface we can uses them interchangeably to the extent defined by the interface. For example we can declare an array that holds objects of type Account. All objects stored in the array need not be from the same class but would need to implement the Account interface. We can count on the objects supporting the interface. We can even create a for loop that runs through the entries, calling a common method.

Example Application Class public class InterfaceDemo { public static void main(String[] args){ Account[] myAccounts = new Account[3]; myAccounts[0] = new Checking(1000, "AMSouth Checking"); myAccounts[1] = new Credit(0, "Visa"); myAccounts[2] = new Credit(0, "Mastercard"); myAccounts[0].debitAccount(100); myAccounts[1].debitAccount(32.95); myAccounts[0].creditAccount(2000); for (int i = 0; i < 3; i++){ myAccounts[i].printBalance(); System.out.println(); }

Events On a computer an event is something that happens that might need the computer’s attention. A key press on a keyboard. The arrival of a packet of information from the internet. A print job completes. A motor stops. etc. When the event occurs an interrupt is generated that stops the processor from doing its current job. At this point the processor can run a separate piece of code called an interrupt handler to deal with the situation. When it is done with the interrupt handler, is can go back to what it was doing before.

Handling an Event In Java, what happens when an event occurs is that the interrupt handler packages up information about what has occurred in an object, called an Event. Then the interrupt handler starts running some Java code called a listener that is assigned to that particular kind of event. We get to create our own listeners so that we can determine what happens when a certain event occurs. It is possible to create our own interrupt handlers and event classes as well, but this is usually done for us as part of an API. leJOS API Swing Android API etc.

Listeners and GUI Programming When creating a graphical user interface (GUI) using event listeners is critical. It would be very difficult to write a loop that would check all the things that might happen. Click on various buttons. Click on various menus. Click in various windows. Type text. etc. Using a loop would also be very slow with many things to check. Finally, it would be expensive in processing power. The processor would spend all of its time checking instead of doing work.

Creating a Listener The leJOS API defines interfaces for the different types of listeners. KeyListener – listen for a certain key to be pressed or released. RegulatedMotorListener – listen for a particular motor to start or stop. FeatureListener – listen for a sensor to detect a particular feature.

Threads When a listener is activated, Java is actually creating a new thread to run the listener. A thread is like a second version of the the program running simultaneously. The two versions of the program share memory but they run independently. When the listener is done with its job, the new thread goes away.

KeyListener As an example let’s look at creating a KeyListener. The KeyListener interface specifies two methods. void keyPressed(Key k) void keyReleased(Key k) If we want to implement the KeyListener interface, our class must have these two methods.

ButtonTest The following code creates a class to crease objects that listen and plays a series of sounds when the appropriate button is pressed. import lejos.hardware.*; class PlaySound implements KeyListener { public void keyPressed(Key k){ Sound.beepSequence(); } public void keyReleased(Key k) {} Notice that the keyReleased method doesn’t do anything, it just needs to satisfy the interface. Similarly, we don’t use the Key parameter, but it needs to be here.

ButtonTest The Key class could be used to determine information about the key that has been pressed. beepSequence is a method of the Sound class that plays a sequence of tones. Now let’s look at and application class that uses an object of the PlaySound class to listen to a key.

ButtonTest public class ButtonTest { public static void main(String[] args){ System.out.println("Press ENTER for a sound."); System.out.println("Press ESCAPE to quit."); Button.ENTER.addKeyListener(new PlaySound()); for(int i = 0; i < 1000; i++) System.out.println(i); Button.ESCAPE.waitForPressAndRelease(); }

ButtonTest This program adds an object of the PlaySound class as a listener for the ENTER key. The program then enters a loop that prints out the integers 0 to 1000. If you press a button while this is going on, it will play the tones and print numbers simultaneously. This shows that two threads can run concurrently. Each thread will be slower because of the limited resources of the EV3 brick.

Button Methods There are several other Button methods. The buttons are identified by the following labels. ESCAPE LEFT RIGHT UP DOWN ENTER In the following code the wildcard <button> can be replaced with any of these labels. Button.<button>.waitForPressAndRelease() – waits for the button to be pressed and released, no return value. Button.<button>.isDown() – returns true if and only if the button is currently pressed. Button.setKeyClickTone(Button.<button>.getId(), frequency) – set the click tone of a button to a given frequency.

Homework Write a program that stores the first 25 Fibonacci numbers in an array and then prints them out. The Fibonacci numbers begin F(1) = 1 and F(2) = 1. After that the formula for the nth Fibonacci number is F(n) = F(n-1) + F(n-2)

Homework Examine the file PetCare.java. This file defines two classes and an interface. Create 3 different pet classes that implement the interface. You should have the pet types respond (print out) appropriately to the different foods and activities. The constructor for each pet should get its name as a parameter and the name should be stored in each pet object. There should be no numbers in your code; use the static fields provided in the given classes. Use the all of these classes to create a program where the user will be asked for 5 pet names and types. Store these pets in an array. Allow the user to indicate a pet index and what they want to do, feed the pet or do some type of activity. Pass this to the pet using the appropriate pet method and see how they respond.

Homework Write an EV3 program that invites the user to press any one of the 6 buttons on the EV3. The EV3 should exit the program if the ESCAPE key is pressed and should make a different sound for each of the other 5 keys. See the website http://www.lejos.org/ev3/docs/ and look at the Sound class in lejos.hardware for ideas about the sounds you could make. Use one or more KeyListener classes to implement your program. (You can have a KeyListener listen to more than one key.)