Sie sind auf Seite 1von 197

COMP02 Instructional Manual

Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

COMP02: Introduction to Information Systems Under the I-Carnegie Module SSD1: Introduction to Information Systems

Unit 1. The World Wide Web 1.1 Using the Web 1.1.1 Surfing the Web 1.1.2 Your Web Pages 1.1.3 Clients, Servers, and URLs 1.1.4 Searching the Web 1.1.5 Commerce on the Web 2 1.1.6 Some Ethical Considerations 1.2 What's in the Web 1.2.1 What's in a Web Page? 1.2.2 A First Look at HTML 1.2.3 A More Detailed Look at HTML 1.2.4 Creating Links to Other Documents 1.2.5 Images and Multimedia 1.3 Writing Web Pages 1.3.1 Organizing the Process 1.3.2 Some Final Thoughts

Unit 2. Introduction to Java 2.1 Reading and Modifying a Java Program

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

2.1.1 Introduction 2.1.2 Reading a Java Applet 2.1.3 How to Run a Java Applet 2.1.4 A Second Look at Java Applets 2.2 Graphics and Variables 3 2.2.1 The Applet, Graphics, and Color Classes 2.2.2 Types, Variables, and Identifiers 2.3 Object-Oriented Programming 2.3.1 Classes, Objects, and Inheritance 2.3.2 Methods 2.3.3 A Review of OOP 2.4 Understanding Classes 2.4.1 Widgets: Buttons and Other GUI Components 2.4.2 Event-Driven Programming 2.4.3 Getting Input from the User 2.4.4 Controlling the Appearance of Your Applet 2.5 Designing a Class

Unit 3. The Java Language 3.1 Java Fundamentals 3.1.1 Arithmetic Operators and Expressions 3.1.2 Boolean Operators and Expressions 3.1.3 Simple Control Structures

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

3.2 Loops 3.2.1 The Need for Iteration 3.2.2 Two Different Loops 3.2.3 Designing a Loop 3.2.4 Testing a Loop 3.2.5 Some Examples of Loops 3.3 Designing Classes and Methods 3.3.1 The Process of Programming 3.3.2 Designing a Simple Class 3.3.3 Designing a Helper Class 3.3.4 Building a Complex Program

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

UNIT 1. THE WORLD WIDE WEB Internet Is a computer network that connects millions of computers across a number of countries Was originally conceived of by the Advanced Research Project Agency (ARPA) of the U.S. government in the 1960s. Network of networks

World Wide Web (or "the Web" for short) Refers to that portion of the computers on the Internet that can communicate with each other using a computer-network protocol called HTTP. All browsers use HTTP to request and receive Web pages from other computers. Two major areas of control 1. Naming of a site on the Web 2. The rules of an Internet Service Provider (ISP). An ISP is any one of a number of companies that enables you not only to connect to the Internet and surf the Web but also to publish Web pages. Search engine is a program that allows one to search for keywords in files at one or more Internet sites. Popular search engines include Lycos, Excite, and AltaVista.

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Client application Requests information from a server application or asks the server to perform some task on its behalf. Typically run on less powerful computers

Server applications Supplies the information Typically run on powerful computers, since they need to be able to service concurrent requests from a number of clients. URL (Uniform Resource Locator) Specifies the location of a Web site (or of a page within the site) Usually begins with an element that identifies the communication protocol to be used to access the file the URL identifies. Also known as Web address

Communication protocol is a generally agreed upon set of standards and rules that machines follow when they communicate with each other. Protocols used in the Internet 1. http Hypertext Transfer Protocol 2. ftp File Transfer Protocol 3. gopher

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

4. news 5. mailto Browsing denotes the activity of following hyperlinks that one encounters on succeeding pages. Searching involves the use of a computer program called a search engine. Search engine is a generic one that refers to a class of programs, though the members of this class may employ very different search mechanisms. Two types of search sites on the Web

Sites that feature a search engine. Sites that feature a Web directory.

Common web-based Internet commerce (also known as e-commerce) Internet Service Providers (ISPs) Advertising Commercial Transactions

HTML stands for Hypertext Markup Language

Language is a term we all understand. A language is a system of signs used for communicationwritten and oral. .

Markup, in paper publishing contexts, is the process of preparing manuscripts for typesetting by marking them with directions about font type and size, indentation, spacing, and the like. In electronic publishing, 6

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

the same principle applies, only instead of marks made by pencil or pen, formatting directions are conveyed by notation called "tags

Text refers to the words on the computer screen that we are marking up. The term "text format" denotes the plain characters of the ASCII (American Standard Code for Information Interchange) character set. As it is, text format is the simplest format in which to store written materials, and text files contain only the 0characters of the ASCII character set

Hyper

should

be

combined

with

the

term

"text"

in

this

discussion. Hypertext as a concept developed from Vannevar Bush's 1932 visionary brainchild known as the "memex," a device that would create links between related topics in different papers, and although the memex was never built, the notion of creating linked, nonlinear structures of information endured. A hypertext document is quite different from a traditional printed document. In a printed document, the order in which information is presented is linearthat is, sentence 1 precedes sentence 2, which in turn precedes sentence 3, and so it goes on up the levels so that chapter 1 precedes chapter 2, which precedes chapter 3, and so on. However, a hypertext document contains links, and by clicking a link, a user is taken to a different page or different part of the same page. If the user then clicks other links, he or she is taken to another page or part of the same page. Thus, the user can follow a nonlinear path through the document or documents, using the links provided by the author and

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

encountering the information there in an order that depends on the choices that both they and the writer have made. HTML is a formatting language use in order to create a web page Tags symbols that tells the browser how to display text. Tags should be enclosed in a pair of angle brackets. The Main Components of an HTML An HTML document should begin and end with this tag pair: <HTML> </HTML> Immediately after the <HTML> tag should be the following tag pair to denote the document header: <HEAD> </HEAD> In between the <HEAD> </HEAD> pair should be the <TITLE> </TITLE> tags. The title of the document is specified within them. This title will be displayed in the title bar of the Web pagefor example, <HTML> <HEAD> <TITLE>My </HEAD> </HTML>

First

Web

Page</TITLE>

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Next come the beginning and ending BODY tags: <HTML> <HEAD> <TITLE>My </HEAD <BODY> </BODY> </HTML>

First

Web

Page</TITLE> >

Almost all of a Web page's content will come between the beginning and ending BODY tags ("<BODY>" and "</BODY>"). Physical Styles Physical style tags allow us to tell browsers to use certain font styles. The following tag pairs force the following styles:

<B> </B> <I> </I> <TT> </TT> <U> </U> <SUB> </SUB> <SUP> </SUP>

Bold Italics Monospace(fixed width) Underline


Subscript Superscript

If an HTML document had the following text: The following is <B>bold</B> while the

following is <U>underlined</U>. It would display like this: The following is bold while the following is underlined.

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Logical Styles When we use logical styles we allow browsers to decide how to display the text. Here are a few of the logical style tags:

<EM> </EM> <STRONG> </STRONG> <CITE> </CITE> <SAMP> </SAMP> sample

Emphasized text Strongly emphasized text Text in citation Text in a computer screen output

There are a few other logical style tags, so you might want to go exploring here. These are used in a manner similar to the way physical tags are used, but the browser decides how to display the text. For example, the following HTML text: The following is <STRONG> strongly emphasized text

</STRONG>. might look like this in Netscape The following is strongly emphasized text. and like this in Internet Explorer The following is strongly emphasized text <hr> - Horizontal Line <br> - Line break
College of Computer Studies

10

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

<pre></pre> - Preformatted Text <font></font> - used to change the Font face, size and color. Two types of List 1. Unordered list <ul></ul> 2. Ordered list <ol></ol> Creating a Table in HTML Document <table></table> - creates a table <th></th> - Table Heading <tr></tr> - Table Row <td></td> - Table Data Two common image files The .jpg extension is used for JPEG (Joint Photographic Experts Group) files. JPEG files are compressedwhich means that the data they contain is stored in a manner that reduces the amount of information needed to reproduce a picture. If the data was not compressed, JPEG files would be much larger and would take much longer to transfer over the Webwhich is what must happen for the images to be displayed by a browser. Also, most browsers store image files on the user's hard drive, so that if the user wants to view an image again, the image can be displayed more quickly by being read from the drive rather than transferred again over the Web. This is an example of a process known as caching, and caching provides yet another reason for compressing image files the larger an image file is, the more room it will take up on a hard drive. 11

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

The .gif extension is used for GIF (Graphics Interchange Format) files. Like JPEG files, the data in GIF files is compressed. The major difference between the two formats lies in the way compression is achieved. The data of GIF files is compressed in such a way that none of the original image information is lost. However, GIF files are limited in the range of colors they support. JPEG files, on the other hand, support more colors, but some of the original image information is lost during compressiona fact that can have an impact on image quality. Therefore, most Web masters recommend using JPEG compression for photographs and GIF compression for other kinds of graphics, such as icons and drawings. It's also important to note here that you do not need to know a lot about compressing or decompressing to use of either of these formats: most graphics packages and browsers handle these processes automatically. For example, if you are working on a photo in PhotoShop, all you have to do is save the photo as JPEG file (an option available through the Save As dialogue), and PhotoShop compresses it in JPEG format automatically. Browsers will then automatically employ the correct decompression technique to display it. The same is true for GIF files.

College of Computer Studies

12

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

UNIT 2. INTRODUCTION TO JAVA A Brief History of Java Java began its life in 1990 as a new language called Oak. Sun Microsystems had established a project group code-named green to develop new products and expand Sun's markets. Oak was originally designed for a personal digital assistant called *7 that Sun intended to market with a seamless graphical user interface. The *7 was never marketed, and eventually Sun formed a company called FirstPerson to develop the *7 in TV set-top boxes for interactive television. Due to a variety of circumstances, the promise of interactive TV soon dried up, and Oak was left without a market. However, about the time that FirstPerson and Oak were failing, the World Wide Web was exploding. Soon companies such as Netscape began to make software that would catapult the WWW into the Internet spotlight. Sun soon realized that Oak had possibilities with the Web, and soon Oak was released to the Internet with a new name: Java. Now Java is in its first release as a development environment, and already it is beginning to influence the direction of computing and the Internet. The Java

College of Computer Studies

13

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

programming language is being released free on the Internet, and Sun is licensing the full implementation of Java and its components to a variety of Internet software vendors in the hopes of creating a new Web programming standard.

About Java Java is a very new programming language and makes possible a very new programming reality. As a commercial product, it is only a few years old, but few new products have captured the attention of the information science, computer science, software development, and programming worlds the way this new language has. One of Javas most attractive features is that it allows you to write a Java program on an Intel computer and then run it on a Macintosh without doing anything special, and that truly is a new programming reality. In its syntax, Java is very much like another popular programming language: C+ +. Unlike C++, however, Java features a number of "building blocks" for creating Graphical User Interfaces (or GUIs, pronounced gooey), making GUIs very easy to implement in Java. However, in order to build meaningful GUIs, a programmer needs to have a grasp of some important programming issues and some fairly complex data structures, and if you are hoping to acquire that kind of skill, you will need to take other courses in addition to this one.

College of Computer Studies

14

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Why Java We are going to use Java to explore basic programming conceptssuch as sequential and iterative execution, simple and complex variables, and program planning. We will also look at some aspects of the object-oriented programming paradigm, and while there are three main object-oriented programming languagesC++, Java, and Smalltalkwe will work only with Java. First of all, Smalltalk is not used by as many programmers as C++ or Java are, and we have chosen Java over C++ and other programming languages for a number of good reasons: Java is portablethat is, as mentioned above, a Java program written for one type of machine (say a PC) can easily work on another machine (say a Macintosh) Java applets can run inside a browser. (In this course, we will work primarily with applets.) Java is used widely for writing Internet applications.

Java Applications vs. Applets Java allows us to write two different types of programs: applications and applets. Java applications are computer programs that run like almost any other computer program. They can be very complex, like the notepad application that many of you used to build your HTML pages, or they can be very simple. Java applications are considered "standalones"which means that they can run on a computer without the aid of another

College of Computer Studies

15

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

application, such as a Web browser. Word processors and spreadsheets as well as Web browsers are all applications. Java applets are programs that are executed from within a Web browser. Put into a Web page, a Java applet can allow users to interact with the page in interesting ways. For example, if your family owned a carpet store, you might want to create a simple calculator that would allow users to enter the size of a room and type of carpet they want, and your carpet calculator would tell them the number of square yards of carpet they need and the approximate cost of the carpet and padding. While your Web page could furnish this information in, say, a table or chart, potential customers might prefer instead to use a calculator applet, simply because it's easier to use. Java Applications vs. Applets Java allows us to write two different types of programs: applications and applets. Java applications are computer programs that run like almost any other computer program. They can be very complex, like the notepad application that many of you used to build your HTML pages, or they can be very simple. Java applications are considered "standalones"which means that they can run on a computer without the aid of another application, such as a Web browser. Word processors and spreadsheets as well as Web browsers are all applications. Java applets are programs that are executed from within a Web browser. Put into a Web page, a Java applet can allow users to interact with the

College of Computer Studies

16

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

page in interesting ways. For example, if your family owned a carpet store, you might want to create a simple calculator that would allow users to enter the size of a room and type of carpet they want, and your carpet calculator would tell them the number of square yards of carpet they need and the approximate cost of the carpet and padding. While your Web page could furnish this information in, say, a table or chart, potential customers might prefer instead to use a calculator applet, simply because it's easier to use.

Below are two Java examples: one is an applet and the other is an application. A Simple Java Applet /* NAME: SECTION: ASSIGNMENT: */ import java.awt.*; import java.applet.Applet; public class Hello extends Applet { public void paint( Graphics g ) { g.drawString("Welcome to } } A Simple Java Application /* NAME: SECTION: ASSIGNMENT: */ public class Hello { public static void main(String args[]) { System.out.println("Welcome to JAVA!");

College of Computer Studies

17

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

JAVA",30, 30); g.drawRect(20, 5, 140, 50); } }

There are a couple of major differences between the application and applet shown above: While the applet executes g.drawString and g.drawRect, the application executes System.out.println. This is because the applet runs in a graphical environment that is, in a browser. For that reason, it can draw graphical elements in the browser (such as lines, circles, rectangles, strings, etc.). In this example, it draws the string Welcome to Java and a rectangle around the string. However, the Java application does not run in a graphical environment. It has to be run in a DOS window (also called a "console window") on a PC. The System.out.println instructs the computer to print the text inside the parentheses to the system's output device. Thus, the message "Welcome to Java!" is printed to the system's output device--in this case, the DOS window (console window). There are a couple of import statements in the applet, while there are none in the application. An import statement makes previously written code available to your program. In this case, the import statements make available the code that is needed to draw a string in a browser. In contrast, the simple Java application draws no graphical elements, and hence it does not need the import statements.

College of Computer Studies

18

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

The Java application includes a method called main( ). The main( ) method is mandatory for all Java applications. When you run the Java application, the machine looks for its main( ) method, and if it cannot find it, the machine will "complain." Applets does not need to include a main( ) methodthe functionality normally provided by the main() method is provided by the browser. Remember that a browser is an application and that applets run inside browsers. Java Applet in Detail The table below breaks our example applet into parts and explains its important concepts. The actual code /* A Simple Java Applet NAME: What it really means The slash-asterisk combination ( /* ) signals the beginning of the comment. From a computer's perspective, a comment is a sequence of characters that it will ignore. From the perspective of the SECTION: computer's human users, a comment usually

consists of statements and information intended for ASSIGNMENT: some purpose, such as making the program's code more understandable. */ The asterisk-slash combination ( */ ) signals the end of the comment. import java.awt.*; import java.applet.Applet; These import statements make code from the packages java.awt and java.applet available to the applet.

College of Computer Studies

19

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

public class Hello extends Everything in Java is written as a class. In this Applet example, the class is named Hello. This line initiates the definition of the Hello class. { This open brace marks the beginning of the body of the class Hello. public paint(Graphics g) { void This line initiates the definition of a method called paint( ). This open brace marks the beginning of the body of the paint( ) method. g.drawString("Welcome This calls the drawString( ) method, which is part of to JAVA",30, 30); the Graphics class. The Graphics class (and, therefore, the drawString( ) method) is defined in one of the imported libraries. g.drawRect(20, 5, 140, This calls the drawRect( ) method of the Graphics 50); } class. This close brace marks the end of the body and definition of the method paint( ). } This close brace marks the end of the body and definition of the class Hello. The simple Java applet analyzed above illustrates well the structure of a Java source file. A typical Java source file (a file with the extension .java) contains a definition of one class, and the example applet above contains the definition of class named Hello. Java requires that the name of the class as defined in a

College of Computer Studies

20

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

source file be the base part of the source file's filename (that is, part of the name before the extension). In the above applet, the class name is Hello; therefore, the source file's filename must be Hello.java. A class definition may contain several method definitions and may (but not necessarily) be preceded by one or more import statements that give the applet access to the code in external libraries. The class definition in the above example contains a definition of a method named paint( ) and is preceded by two import statements. In the following sections, we will analyze these chief components of a Java program (import statements, classes, and methods) in more detail. Import Statements Java import statements "import" (and, hence, give our applets access to) Java code libraries that contain code already written to do tasks we might want our applets to do. Of course, the capacity to import code libraries is not unique to Java: many serious programming languages have that capacity. Code libraries are simply collections of previously written classes, methods, and functions that are ready to be executed and can be used in other programs. The classes, methods, and functions that libraries contain perform functions that are needed by a variety of programs. Collecting these elements into libraries provides developers with a set of "building blocks" that are ready to use. Java code libraries consist of packages. Each package consists of a number of previously written classes. For example, java.awt is a package;

java.applet.Applet is a class in the package java.applet. As we see, a name of a package or a class in Java is a set of words delimited by dots. To use the

College of Computer Studies

21

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

methods of a pre-built class in our program we need to import this class using the import statement. We could choose to import a particular class or a whole package with all its classes. Also, all import statements are usually specified at the beginning of a program. Now, let's analyze the two import statements in the applet above. import java.applet.Applet; This statement imports the class Applet that is contained in the package java.applet. The Applet class contains the code that allows us to run our program as an applet in a Web browser. import java.awt.*; This statement imports all classes in the package java.awt (by the way, awt stands for Abstract Windowing Toolkit). This package contains programs that can build the window and do the type of drawings we need to do. The asterisk ( * ) that follows the statement's last period ( . ) is a "wildcard character" and tells Java to import all classes in the package. It turns out that the language Java "knows" very little. On its own, it can do a little arithmetic, allocate memory for data, store data in the allocated memory, make simple true-or-false tests, and repeat things. That is not muchbut that is all a programming language really needs to be able to do. Whenever we write a program, we need to decide which parts of the program we should write from scratch ourselves and which parts can make use of code written by others and made available in libraries. In general, we want to make as much use of the code available in libraries as possible. This is somewhat analogous to deciding

College of Computer Studies

22

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

whether to build a building out of bricks made by someone else or out of bricks we make ourselves from scratch. Also, be aware that the library structure for Java is very large and is still evolving, and in this course, we will use only a few pieces of a few libraries. Therefore, if you want to be a Java programmer, you will need to learn a lot more about the various libraries than we will cover in this course. Classes, Objects, and Methods Everything in an object-oriented language like Java is written as a class. Class refers to the structure and behavior of a category of objects. The structure specifies the data that is contained in the category of objects, while the behavior specifies the actions that can be performed by the category of objects. The behavior collectively refers to the set of methods that the class can execute. An object is an instance of a class. An object is a self-contained entity that has both the data and the means to act on the data. The example applet and application above each have one method only (paint( ) in the applet and main( ) in the application), and there are no structures or data in either of theseat least no data that we can see at the present. Now it is time to look at some of the rules for writing Java classes. There is an isan-instance-of relationship between an object and its class. As a short form, an is-an-instance-of relationship is also called an is-a relationship when there is no possibility of misunderstanding. As we mentioned earlier, a class denotes a category of objectsjust as in English the term Elephant refers to a category of things in the world: elephants. When we talk about Elephant, we talk in

College of Computer Studies

23

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

generalities and not about any one elephant in particular. Similarly, in programming, a class refers to a category of objects and not to a particular object. For example, a class Elephant describes a category of elephant objects. An object is-an-instance-of a class. As a convention, when we refer to a class, we will uppercase the first letter of the class's name, and when we refer to an object, we will lowercase the entire object name. In the real world, elephants have attributes such as height, weight, etc. They also do things such as walk, drink, etc. Similarly, in programming you can define a set of attributes that a class can have and a set of activities (called methods) that it can perform. Class Definition Classes are the major organizational block for Java programs. A Java program consists of one or more classes. Within this course, each class is defined in a separate source file. The definition of a class specifies what the class has and what it can do. Within a class, we can import and use other classes. If you look at the first line of the definition of the class Hello, you will see the following: public class Hello extends Applet Lets look at each of this line's elementsbeginning with public We can specify a Java class as public, private, or protected using the keywords public, private, and protected; however, for now we will work only with classes that designated public. By specifying a class as public, we are saying that the

College of Computer Studies

24

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

class is available to be accessed by any code that can access the package in which the class is declared. class The keyword class indicates that the statement is a definition of a class. Hello Hello is the name of the class. As we mentioned earlier, class names by convention should begin with a capital letterand, as you see, this example follows that convention. Note: for reasons we won't go into now, you must not change this name. We will look at these reasons later and show you what you must do if you want to change this namebut for now, please realize that if you change this name, your program will probably not run. extends Applet Read the phrase extends Applet to mean that the class being defined "descends from," "inherits from," or "is a child of" the class Applet. That is, our class Hello is a child or a subclass of a class named Applet. In turn, class Applet is called the superclass for the class Hello. This means that Hello can do anything that the parent class Applet can do. The parent in this case "knows" how to execute itself within a Web page. Since we have declared our class Hello as a child of Applet, we dont have to write all of the needed Java instructions required to run the program in a Web page. Class Hello inherited this ability from its parent class Applet. In Java, the mechanism by which a child class acquires functionality defined in a parent class is called inheritance. There are other methods in class Applet that class Hello can inherit and use. Some of these methods are init( ),

College of Computer Studies

25

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

start( ), stop( ), and update( ). Notice that our class Hello has its own paint( ) method. This is fineJava will use our definition of paint and ignore the definition of paint( ) in the class Applet. If we leave out a definition of a method, Java automatically relies on the parent's definition. The following is the body of the Hello class: { public void paint( Graphics g ) { g.drawString("Welcome to JAVA",30, 30); g.drawRect(20, 5, 140, 50); } } This class body is bounded by or delimited by a pair of braces. The last character of the class must always be a closing brace ( } ). All of the Java code found within these brace delimiters is part of the class. Methods and Method Definitions There are two main components of a Java class: 1. data (also called the structure) 2. methods (also called the behavior) All of the structure (data) and behavior (methods) of a class have to be defined in the body of the class. That said, as you may have noticed, there is no data stored in the Hello example class. However, there will be data in some of our future programs, but that will have to wait for a while.

College of Computer Studies

26

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

In Java, methods are groups of instructions that have names. Methods enable our programs to do things. Note that other languages use other terms to refer to what in Java we call methods. In Fortran, the term is subroutine; in Pascal, it is procedure; in C, it is function; and in C++, it is member function. In order to have the computer execute the instructions in the body of one of our methods, the method must be invoked or called. We have a very interesting situation when we write applets: some of our methods are called for us automatically when we run the appletand others are not. For example, the paint( ) method is called automatically when we start the applet and is called anytime it is needed. Inside the body of class Hello, the first thing we see is a definition of a method named paint( ). The method definition consists of the method's name, followed by a set of parentheses. Sometimes these parentheses will contain parameters. A parameter is a piece of data that is provided to the method when that method is called. After the parentheses is the body, enclosed in braces. Let's dissect this method: public void paint( Graphics g ) The keyword public tells Java that this method can be used by other classes outside of the class Hello. Remember that somewhere, somehow, our paint( ) method is called for us automaticallyso our method paint( ) must be defined as publicly accessibleotherwise our applet will not be able to run. For now, all of our methods will be defined as public.

College of Computer Studies

27

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

The keyword void means that a method does not return a value. Methods can do three things: They can draw. They can compute and return values, such as an average of a list of numbers. They can do both of the above. For now we will use only void methodsthese are methods that do things but do not return values. Following the keyword void is the method name: paint( ). (Graphics g) Following the method name in our example is a list of parameters enclosed in a pair of parentheses. This is the list of resources the method needs to do its job. Some methods, however, need no parameters at all, and, therefore, feature a set of empty parenthesesa method definition must have the parentheses, even if the parentheses are empty. However, in our example, the parentheses contain one parameter: g. The "Graphics" inside the parentheses is the name of a class defined in one of the imported libraries (the fact that it is capitalizes clues you in to the fact that it is a class, since the convention is to capitalize class names). By writing "Graphics g", we are indicating that g is an object of the Graphics class. Note here that since the parameter we are specifying is to be an object of the Graphics class, we must specify the class name "Graphics" exactly as it is shown above, but the object name can be anything we choose. Here we give it the name g, but we just as easily could have named it gr or myGraphicsObject or any other meaningful name. Any object of the class Graphics "knows" how to draw things in an applet

College of Computer Studies

28

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

window, how to change color, and how to print words. By placing this parameter in the parentheses, the method paint( ) is being given a resourcean object named g of the Graphics classwhich knows how to draw. The paint( ) method can now use this object to draw things in the applet window. It is very similar to me asking you to write something for me on a piece of paper and loaning you my pen to do it. The loaning of the pen is very similar to putting "Graphics g" in the parameter list. The body of the method is delimited by a pair of braces, just as the body of the class is. Everything within this set of braces is part of the paint( ) method. You can define methods within classes, but you cannot define classes within methods, and you cannot define methods within methods. Inside of the body of paint( ) there are two statements. The first statement draws a string "Welcome to JAVA" at the location x:30, y:30: g.drawString("Welcome to JAVA", 30, 30); The next statement given below draws a rectangle 140 pixels in length and 50 pixels high at the location x:20, y:5: g.drawRect(20, 5, 140, 50); Four steps in Creating a Java Applet 1. Write Java code that will constitute the applet. To write code, you will use an editor. You will save the Java code in a source file ( .java file). Note that all java source files should have a .java extension. Furthermore, the file in which you put the source code for a class should have the same

College of Computer Studies

29

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

name as the name of the class extended with .java. In the above example, the class Hello should be placed in a file named Hello.java. 2. Compile the Java source code in the .java file into bytecode using a Java compiler such as javac that is a part of Java Development Kit (JDK). The result of compilation will be a bytecode file. Note that all bytecode files will have the extension .class. In our example, the bytecode file generated from the source file Hello.java will be named Hello.class. 3. Create a HTML file that embeds this bytecode file in a pair of APPLET tags that specify the location of the Java applet the size (that is, the width and height) of the area occupied by the applet in the browser or applet viewer. 4. Run the applet by opening the HTML file in a Web browser or an applet viewera special "minimal" browser for running applets that is also included in Sun's JDK.

College of Computer Studies

30

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Note that the steps necessary to run a Java application are slightly different. Below is a diagram of the process of compiling and running a Java application. After compiling your application's source file with the javac compiler, you will get a .class file. This .class contains the Java application. You will run this .class file using the JDK Java interpreter called java. Web browsers and applet viewers can't run Java applications. Pay particular attention to the following when creating an Applet: Spelling. The case of letters. Java treats "import" and "Import" as different wordsif you type "Import", your program is wrong! Matching sets of parentheses ( ) and braces { }. These are called delimiters and must come in opening-closing pairs. The punctuation marks. In this program they include the period ( . ), semicolon ( ; ), quotation mark ( " ), and comma ( , ). Special symbols. These include the asterisk ( * ) and slash ( / ).

Source code is the program written in Java or other high-level programming language by the programmer. Source code can be read by humans. Source code is stored in source files. The Java program you saw in the previous page is the source code of the Hello applet. Compilation is the process of converting high-level source code into machine language or another form that can be executed by the machine. While high-level source code can be easily understood by humans, the low-level machine

College of Computer Studies

31

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

language is a form that is extremely strenuous for humans to follow, while extremely easy for machines to interpret. Compiler is a computer program that performs compilation. In our course, you will most likely be using a Java compiler named javac that is a part of the Java Development Kit (JDK). There is more help on installing and using JDK in the appendix section on setting up your Java environment. From your Command Prompt window (also called a DOS console window), you can call the Java compiler javac to compile the source code file Hello.java with the command: javac Hello.java Compiling a Java source file produces a bytecode file. Bytecode is a special intermediate-level format that can be run by the Java Virtual Machine. Files that contain bytecode have a .class extension. When you compile Hello.java using the Java compiler javac, it produces the bytecode in a file called Hello.class in the same directory. This file is written and named by the Java compiler, and its name is always the same as the name of the class defined in your Java program with a .class extension appended. The result of a successful compilation of your Java program is always at least one .class file. Bytecode is not a low-level machine code. It can't be directly executed by your computer. Bytecode has to be executed by the Java Virtual Machine, or JVM. Although JVM has the term machine in it, the machine refers to a software implementationthat is, an abstract machine. When your bytecode is run inside the JVM, the bytecode is translated into real machine code that can be run by the

College of Computer Studies

32

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

physical machine. All Java interpreters, Java-enabled browsers, and applet viewers have a JVM inside and can execute bytecode. The JVM acts as an intermediary between the real computer and your bytecode. By having a twolevel architecture with bytecode as intermediate-level representation and the JVM acting as an abstract machine, Java achieves portability across computer platforms. That is, you can run your bytecode on a Sun computer or a Macintosh computer, or any other computer that has a JVM implementation. Currently, JVM is implemented for most existing computer platforms. Creating the HTML File A Java applet is invoked (run or executed) from within a Web page. A call of an applet has to be embedded inside some HTML document. Here is the simplest form of an HTML document that will run our applet Hello. Convention dictates that you name this file Hello.html, but that is just convention and not a Java rule (unlike the case with Hello.java). <HTML> <BODY> Here is the Hello applet: <APPLET code = "Hello.class" width = 200 height = 75> </APPLET> </BODY> </HTML>

College of Computer Studies

33

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

The APPLET tag in the HTML file "tells" the applet viewer or Web browser three pieces of information: code = "Hello.class" width = 200 height = 75 The first list item literally says that the applet to be executed is called "Hello.class". As you remember, javac created Hello.class from Hello.java when you compiled the Hello.java program. The second and third list items tell the browser or applet viewer how big the applet window must be. When a Web browser or the applet viewer executes or runs your applet, it builds a window 200 pixels wide and 75 pixels high and executes the bytecode instructions in the file Hello.class. The unit of measure is pixel, which is short for picture element. The graphics display for your computer is composed of thousands (or millions) of these individual elements; thus the pixel is the smallest piece of visual information that your monitor can display. It is about the size of a period ( . ), like the one at the end of this sentence. Running the Applet Running the applet is done by using a Web browser or the applet viewer provided by Sun as a part of the JDK. An applet viewer is a special program that could run applets. It could be considered a stripped-down Web browser that can't display HTML, but can locate an applet inside a Web page and run it. Both the browser and the applet viewer require an HTML document that invokes or embeds the applet.

College of Computer Studies

34

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

All browsers that are java enabled (that is, they include the JVM) can understand and execute your bytecode. And most popular browsers such as the Internet Explorer and Netscape Navigator are Java enabled. This is one of the reasons for the remarkable popularity of Java. However, different browsers have slight variations in the way they execute applets. We suggest that you use an applet viewer provided with your JDK as the definitive tool to check your work. Components of a Java Applet The typical Java applet is made up of numerous components that include keywords, structures. Keywords Keywords are words that have a special meaning in the Java language. Keywords are used to form different programming constructs.. abstract boolean break const finally int public this float return throw for short byte goto native static case if new catch char class instanceof protected synchronized identifiers, statements, classes, methods, and control

continue default do interface long

double else package void

extends final private switch

implements import

strictfp super

throws transient try

volatile while

The applet listed earlier in this page contains the following keywords: import - is used to make parts of a library available for use in the current program. public - means that other classes may use this class or method during their execution.

College of Computer Studies

35

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

class - tells Java that this is the beginning of a class declaration. extends - tells Java that the class named before the keyword extends is a subclass of the class named after the keyword. (For example, the code "public class Hello extends Applet" tells Java that Hello is a subclass of Applet.)

void - means that this method will not return a value.

Identifiers An identifier is a name. In Java, an identifier can be a class name, a method name, or a parameter name. For example, the class name Hello is an identifier. Similarly, the name of the parameter g is also an identifierand so is the method name paint. The syntax of identifiers is very important. Identifiers can use alphabetic characters of either case (az and AZ), numbers (09), underscores ( _ ), or dollar signs ( $ ). No other characters are allowed. No commas, hyphens, etc. Also, identifiers cannot start with a number. Finally, keywords cannot be used as identifiers (for this reason keywords are sometimes called reserved words). The following are valid The following are not valid identifiers identifiers student pie_Master pieMaster pie4 pie2pie dollar$man pieMethod $dollarman 4pie pie-pie pie,pie

pie/cake method void

College of Computer Studies

36

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Statements Statements are the basic units of execution in a program. They tell Java to do something. This program has the following statements: import java.applet.*;

import java.awt.*; g.drawString("Welcome to JAVA", 30, 30); g.drawRect(20, 5, 140, 50); These statements result in some action being performed. Some of the actions are invisible to the user of the applet. The user will never actually see the import statements being executed because they are directives to the compiler. The g.drawString statement will result in a visible action because the string Welcome to JAVA will be displayed in the applet window. Statements have one thing in commonthey end with a semicolon ( ; ). Where there is no semicolon, there is no statement. The body of the method paint( ) in our example has two statements: g.drawString("Welcome to JAVA", 30, 30); g.drawRect(20, 5, 140, 50); Finding and Fixing Errors When you modify the Java program, you may encounter some errors when you compile it. We will soon learn what those errors mean and how they can be fixed. Sometimes it's a matter of a missed comma or semicolon.

College of Computer Studies

37

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

In all disagreements with the compiler, the rule is simple: the compiler always wins. The author typed in the Hello Java applet program and left out the semicolon at the end of the second line shown belowthe "_" is where the missing semicolon should be: import java.awt.*_ Here's what was typed on the command line (it was supposed to compile a Java program): >javac Hello.java And here are the error messages issued by the compiler: Hello.java:6: ';' expected. Format: number:message. message indicates filename:line This that it error has

detected a problem on line number 6: a missing semicolon. import java.awt.* Here the compiler displays the line of code where the error might be. ^ The compiler then places a caret ( ^ ) under the line of code where the error might be. Hello.java:8: Superclass Applet of class A second error messagethis one Hello not found. flagging line number 8 as a possible location of an error. But, beware, there is actually no error on line 8!!! public class Hello extends Applet Again, the compiler displays the line

College of Computer Studies

38

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008 of code where it thinks the error is.

Again, compiler places a caret ( ^ ) under the line of code where the error might be.

2 errors

This is the total number of errors

found. Now, if a semicolon is put in line 6, where it belongs, both of these errors will disappear. As indicated above, the basic message format gives the file name and then the number of the line on which the error might be located. Just remember that the error message represents the compiler's best guess at what is wrong. The best way to get introduced to Java error messages is by experience. Your initial exposures will probably be frustrating, but that will pass. Once you have corrected all of the errors, you can run your program in applet viewer or Web browser. Errors are a part of a programmer's lifewe all make them. It turns out that writing a program takes a much higher degree of perfection than most of us are used to achieving, and the simplest error can keep our programs from running. And once our programs run, we must continue evaluating and testing them to make sure they are running correctly. Some programs are so complex that they defy complete testing for correctness. Fortunately, you will not write such programs in this class, but some of the ones you will write will be difficult to test exhaustively.

College of Computer Studies

39

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

When you wrote Web pages in the previous unit, you probably made two types of errors: syntax errors execution errors

Syntax errors occurred when you used the wrong tag or left out a closing tag or a closing angle bracket. A syntax error would cause angle brackets to be displayed in your Web page when viewed in a browser. The fact that the Web page is displayed at all is due to the fact that the browser ignores HTML syntax errors and displays the page regardless. You can think of syntax errors as errors in grammar. Just as grammatical errors in English lead to ill-formed sentences, syntax errors in programming lead to illformed programs. Humans are smart enough to infer the meaning of a sentence, even if the sentence is ill formed. But, compilers are not that smart. They will complain, and you have to fix the error. Execution errors are also called "logical errors." For example, maybe you wanted something displayed as bold or centered, and that something was instead displayed as italic or left justifiedthat is an execution or logical error. The browser did what it was told to do, and the syntax of the HTML was correct, but the result was not what you wanted. There is a story about a king who intended to spare the life of a particular prisoner, and one day when the king's jailer sent him a letter asking, "What do you want to do with this prisoner, kill or spare him?", the king, being pressed with many other matters, wrote back a terse reply. Unfortunately, although the king had intended with his reply to order the

College of Computer Studies

40

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

prisoner's life spared, in his haste to write "Kill not, spare" he misplaced the comma and wrote "Kill, not spare." Thus, the king's statement illustrates what we have called a "logical error." The statement is grammatically correct, and the jailer could, therefore, understand and obey it as an answer to his question; but it did not accomplish what the king had intended, because the prisoner was killed. When you write programs, you will most likely also run into such logical errors (though not as fatal). You should test your programs to see if they do what you intended them to do. Again, execution errors are not errors in grammar: if the king's grammarians had examined his statement, they wouldn't have found an error. Similarly, a compiler (which is a type of grammarian) will not usually complain about logical errors; logical errors usually manifest themselves at run time, not compile time. Both of these types of errors (syntax and logical) can also occur in a Java program. However, Java is somewhat pickier about syntax. Your browser never refused to display your Web pageit just ignored your syntax errors. In fact, a syntax error that causes a very bad display in one browser may not cause a bad display on another browser; this is why you must test your Web pages on different browsers. If you have a syntax error in a Java program, it will not compileand Java will output a list of cryptic error messages. Once you have decoded the error messages and fixed the errors (more evaluation/testing, planning, and coding) you will have eliminated the syntax errors. Then you must run the applet to see if it does what you intended it to do.

College of Computer Studies

41

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Four final thoughts about syntax errors: 1. The Java compiler will provide, at best, a guess of what the error is and where it occurred. Sometimes it is correct and shows you where to fix the error. Sometimes it will mark a place that contains no error. If you find no error visible, check the code above the marked line. You may have made a mistake one, two, or more lines above the indicated place. 2. If the Java compiler prints a long list of errors, you should consider only the first one or two to be truly valid. It is possible that the first syntax error led the compiler down a very wrong path to find other errors that are not really errors at all. Fix the first one or two errors and recompile your program. You may find that the other errors are no longer in the list. 3. The opposite of item two can occur. You compile and get two errors. You fix them, and the next compile generates twelve errors. What happened? Java found the first two errors and for various reasons stopped compiling the program. Java literally "did not see" the rest of the errors. Once you fixed the first two errors and recompiled, Java was able to "see" the next set of errors. This leads to one major piece of advice that will be important to you when you write your first original program: compile frequently and fix the errors as you go. It is usually not a good idea to write an entire program from the opening comment to the last "}" and then start compiling it for the first time. Seeing a list of 354 errors can be very depressing. 4. If you read an error message and it makes no sense, get help. If you read an error message and understand it but cannot find the actual error, look

College of Computer Studies

42

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

again. If you spend more than 23 minutes in this state, get outside help. Ask your teacher, or, if it's allowed, ask another student to look at your code. Just staring at code rarely helps you find errors. Get helpan outside pair of eyes can find things at a glance that you, as the original author, might never see. Commenting Your Code Documenting code is one important task for which software developers are responsible. One element of documenting code correctly is including comments within the code. Commenting code is very important because it makes the code easy to maintain thus making the software's total cost of ownership less expensive than it is for code that is not well commented. When code is well commented, it is less costly to maintain because any developer who is maintaining it requires less time to understand the codes purpose and how the code works. When you are writing comments, you should assume that the reader of the comments will be a developer of average competence who knows nothing about the classs purpose or how the code functions. Well written comments should explain the purpose of the class somewhere near the beginning of the class. Each method should have at least one comment placed immediately before the method name explaining the purpose of the method and how the method performs its function. Any complicated approach that you used to accomplish the methods function should be brought to the attention of the reader in order to

College of Computer Studies

43

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

minimize the time required by the developer to understand how the code functions. All of the classes that you submit should be commented. Comments can be created in two ways. One method that can be used to create a comment is to begin the line of code with a // symbol. Two examples follow. // The purpose of this class is to compute the average of two numbers. Or, average = (num1+num2)/2; // computes the average of two numbers. In the above examples, all text appearing after the // AND on the same line will be considered to be a comment. This approach is typically used when the comment is short in length. Comments are not compiled when the class is compiled. Comments are not considered to be java statements. If the comment wraps to a new line and that line does not begin with a // symbol, the compiler will not treat it as a comment and a compile error will be generated. Sometimes the comment is placed immediately before the line(s) of code that it is intended to document, as shown in the first example above, and sometimes the comment is placed on the same line as the line of code that it is intended to document, as shown in the second example above. Either approach is acceptable. Sometimes, a comment that spans several lines is needed. In this situation, the comment can be created by beginning the comment with a /* symbol and ending it with a */ symbol. For example, /* This class accepts from the user a name to display and a color in which to

College of Computer Studies

44

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

display it. Upon accepting the user's input, the value of the name is stored in a variable called strName and the value of the color is stored in a variable called strColor. */ In the above example, all text between the /*' symbol and the */' symbol is a comment. Graphics and Variables java.applet Provides the classes necessary to create an applet and the classes an applet uses to communicate with its applet context. Then the paint method is called to display the output.

java.awt Contains all of the classes for creating user interfaces and for painting graphics and images.

java.awt.event Provides interfaces and classes for dealing with different types of events fired by AWT components.

Applet class must be the superclass of any applet that is to be embedded in a Web page or viewed by the Java Applet Viewer. provides a standard interface between applets and their environment.

College of Computer Studies

45

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Class Applet java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--java.awt.Panel | +--java.applet.Applet

init - public void init() Called by the browser or applet viewer to inform this applet that it has been loaded into the system. It is always called before the first time that the start method is called. A subclass of Applet should override this method if it has initialization to perform. For example, an applet with threads would use the init method to create the threads and the destroy method to kill them. start - public void start()

College of Computer Studies

46

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Called by the browser or applet viewer to inform this applet that it should start its execution. It is called after the init method and each time the applet is revisited in a Web page. A subclass of Applet should override this method if it has any operation that it wants to perform each time the Web page containing it is visited. For example, an applet with animation might want to use the start method to resume animation, and the stop method to suspend the animation. stop - public void stop() Called by the browser or applet viewer to inform this applet that it should stop its execution. It is called when the Web page that contains this applet has been replaced by another page, and also just before the applet is to be destroyed. A subclass of Applet should override this method if it has any operation that it wants to perform each time the Web page containing it is no longer visible. For example, an applet with animation might want to use the start method to resume animation, and the stop method to suspend the animation. destroy - public void destroy() Called by the browser or applet viewer to inform this applet that it is being reclaimed and that it should destroy any resources that it has allocated. The stop method will always be called before destroy. A subclass of Applet should override this method if it has any operation that it wants to perform before it is destroyed. For example, an applet with threads would use the init method to create the threads and the destroy method to kill them.

College of Computer Studies

47

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

paint - public void paint(Graphics g) Paints the container. This forwards the paint to any lightweight components that are children of this container. If this method is reimplemented, super.paint(g) should be called so that lightweight components are properly rendered. If a child component is entirely clipped by the current clipping setting in g, paint() will not be forwarded to that child. Overrides: paint in class Component Parameters: g - the specified Graphics window update - public void update(Graphics g) Updates the container. This forwards the update to any lightweight components that are children of this container. If this method is reimplemented, super.update(g) should be called so that lightweight components are properly rendered. If a child component is entirely clipped by the current clipping setting in g, update() will not be forwarded to that child. Overrides: update in class Component Parameters: g - the specified Graphics window repaint - public void repaint() Repaints this component.

College of Computer Studies

48

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

This method causes a call to this component's update method as soon as possible

Defining Classes public class classname { Declaration of instance variable1; Declaration of instance variable2; ... Declaration of other instance variables ... Definition of method1 Definition of method2 ... Definition of other methods ... } Comments and White Space Remember that Java ignores white spacesuch as blanks, tabs, empty lines, etc.between words in programs. Note that white space inside a string (anything inside a pair of quotation marks is a string) are not ignored. Example: "This is a string". Also note that anything in a line that comes after a pair of slashes ( // ) is a comment. Comments are for the human reader, and the Java compiler will ignore them. Thus, when the compiler sees a pair of slashes, it ignores the rest of the line. You can also mark something as a comment by enclosing it between

College of Computer Studies

49

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

a slash-asterisk ( /* ) and an asterisk-slash ( */ ). Anything that falls between the comment delimiters /* and */ will be ignored by the compiler. Sample Class import java.awt.*; import java.applet.Applet; public class Person { // Attributes of Person as shown below public String name; public int age; public int height = 80; public String sex; public void drawPerson (Graphics g, int x, int y) { // draws the person, anchored at (x,y) // draw head g.drawOval(x, y, 20, 30); g.drawArc(x+12, y+6, 6, 9, 200, 135); g.drawArc(x+3, y+6, 6, 9, 200,135); g.drawOval(x+7, y+20, 6, 5); //draw body g.drawLine(x+ 8, y + 30, x+ 8, y + height);

College of Computer Studies

50

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

g.drawLine(x+12, y + 30, x+12, y + height); //draw arms g.drawLine(x + 8, y + 30, x, y + 40); g.drawLine(x, y + 40, x + 8, y + 50); g.drawLine(x + 12, y + 30, x + 20, y + 40); g.drawLine(x + 20, y + 40, x + 12, y + 50); //draw feet g.fillRect(x, y + height, 10, 3); g.fillRect(x+11, y + height, 10, 3); } } import java.awt.*; import java.applet.Applet; public class PersonApplet extends Applet public Person joe; // joe is an instance variable. public void init() { /* init() is called only once. This is where the applet is initialized.*/ joe = new Person(); // Create a new object instance for Joe Hamilton. } public void paint ( Graphics g ) {

College of Computer Studies

51

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

joe.drawPerson(g, 20, 15); // Draw joe on the applet. } Inheritance Inheritance is used to specify an is-a-kind-of relationship between two classes. Inheritance provides a formal mechanism for code reuse. Definition: A subclass is a class that derives from another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a class's direct ancestor as well as all of its ascendant classes.

import java.awt.*; public class Prof extends Person { // attributes of Prof as shown below public double salary; // methods of Prof public void drawBBoard(Graphics g, int x, int y) { // Draw the Black Board // Draw a brown colored rectangle Color c = new Color(200, 165, 135); g.setColor(c); g.fillRect(x, y, 80, 65);

College of Computer Studies

52

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// Draw a black colored inner rectangle g.setColor(Color.black); g.fillRect(x + 4, y + 4, 72, 57); } public void drawProf(Graphics g, int x, int y) { drawPerson(g, x, y); drawBBoard(g, x + 25, x + 2); } Overriding Overriding is the process of writing a method in a subclass that has the same name as a method in the superclass and takes the same parameters. import java.awt.*; public class ProfPointing extends Prof // draws the person, anchored at (x,y) public void drawPerson (Graphics g, int x, int y) { // draw head g.drawOval(x, y, 20, 30); g.drawOval(x + 11, y + 11, 5, 3); // right eye g.drawOval(x + 3, y + 11, 5, 3); // left eye g.drawOval(x + 7, y + 20, 6, 3); // mouth

College of Computer Studies

53

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

//draw body g.drawLine(x + 8, y + 30, x + 8, y + height); g.drawLine(x + 12, y + 30, x + 12, y + height); // draw arms // right arm (appears to the left) g.drawLine(x + 8, y + 30, x, y + 40); g.drawLine(x, y + 40, x + 8, y + 50); // left arm g.drawLine(x + 12, y + 30, x + 20, y + 40); g.drawLine(x + 20, y + 40, x + 28, y + 30); //draw feet g.fillRect(x, y + height, 10, 3); g.fillRect(x + 11, y + height, 10, 3); } public void drawBBoardInfo(Graphics g, int x, int y, String str) { g.setColor(Color.white); g.drawString(str, x + 10, y + 45); } public void drawProfPointing(Graphics g, int x, int y) { drawProf(g, x, y); drawBBoardInfo(g, x + 25, y + 2, "2 + 3 = ");

College of Computer Studies

54

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

} } Naming Conventions for Instance Variables and Classes The syntax of Java identifiers is important, as are the naming conventions that identifiers follow. The conventions are for Java followed identifiers "rules" are that

straightforward.

Conventions

generally

programmers use. Conventions are not rules in the real sense, since their violation will not prevent Java programs from compiling. But following these 'rules' will make it easier for you and others (especially the person who grades your programs) to read your code. Some of these conventions are: Begin identifiers for instance variables with lowercase letters. To make identifiers more meaningful, it is suggested that you use multiword identifiers for instance variables, and thus make your code more readable. Instance variables should be nouns, noun phrases, or abbreviations for these. For example, a variable to keep track of the number of employees in the system might be numEmployees. Notice that two words are used in this identifier and that there are no embedded spaces. Also notice that the first word, num, a short form for 'number,' begins with a lowercase letter while the second word, Employees begins with an uppercase letter. Instead of numEmployees, we could have used ne, but that is not meaningful to someone else, nor to us six months down the road. We

College of Computer Studies

55

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

could have used Number_Of_Employees, but this is not general Java convention. Identifiers for local variables and parameters should be short and meaningful. They usually do not contain whole words. One letter identifiers such as i, k, and xshould be avoided except for temporary variables or loop variables, which we will see later in the course. The names of classes should be short and descriptive nouns or noun phrases. The first letter of a class name identifier should begin with a capital letter. The remainder of the class name follows the conventions of variable identifiers. Class names should be truly descriptive of what the class represents. Writing a Method The general syntax for a method is: public returnType methodName (TypeOfParameter1 param1,

TypeOfParam2 param2,...){ type1 localVariable1; type2 localVariable2; ... statement1; statement2; ...

College of Computer Studies

56

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Conventions for Naming Methods An identifier cannot start with a number and can consist of numbers (09), letters (az, AZ), dollar signs ( $ ), and underscores ( _ ). Note that method names are also identifiers, so they should follow the rules for creating identifiers. The general naming convention for methods is to use a verb or verb phrase. If the method name consists of more than one word, the first word is in lowercase letters; the subsequent words start with an uppercase letters. For example, the makeDean( ) method above follows this convention for multi-words. Both makeDean( ) and promote( ) follow the convention of using verbs or verb phrases. Type Casting a value of one type can be converted into a value of another type. This is called type casting. For example, when you round up the double value of 3.1714, you can get the integer 3. This is akin to taking some inedible thing, and making it into food. For example, cinnamon on its own is not edible, but you can add cinnamon to something else, and eat it. So, when you are changing the type of cinnamon from non-food into food, you are doing type casting. In type casting, there is a source type and a target type. Value of source type has to be converted to the value of target type. Type casting can happen in two different ways: Java can do it automatically for you. There are specific conditions where automatic type conversion can happen. 57

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

The programmer can explicitly specify type casting.

Calling a Method Method calls follow two patterns: One pattern is for a method of a class to call another method belonging to the same class. To call methods in the same class, we simply use the name of the method followed by a pair of parentheses. Another pattern is for a method of a class to call a method belonging to a different class. To call a method belonging to a different class, we specify the name of the object and a dot or period ( . ) after the object name, and then the method name. Beyond Displaying Images and Text The Java language provides a set of objects that allow users to interact with programs. These objects are graphical in nature and usually require a mouse click for some part of the interaction. They are commonly called widgets in GUI jargon, and they make up a family of elements we can use to build graphical user interfaces (or GUIs). Class Hierarchy A part of the class hierarchy for the class Component is given below.

College of Computer Studies

58

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Everything in the drawing that is below Component is a subclass of Component. Label Class The class Label has three constructors. Button Class The Button class will be used extensively for user input. The Button class has two constructors and two methods that get and set the label that is displayed inside the button.. TextComponent Class

College of Computer Studies

59

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

The TextComponent class is an abstract class, so it has no constructor. The one TextComponent method to remember is setEditable( ), TextField and TextArea The TextField and TextArea classes are both subclasses of the TextComponent class. The TextField class has four constructors that enable one to build the exact TextField object that is needed. TextArea objects are very similar to TextFields. However, whereas TextField objects allow users to input a single line of text only, TextArea objects allow them to input multiple lines of text. A Simple Example: Labels, TextFields, TextAreas, and Buttons

/************************************************************* * SSD1->Introduction to Java->Understanding Classes->Widgets * * Widget examples * * Attention: * * * The code here uses a few concepts that have not yet been introduced. Use this applet just as a graphical illustration of widgets.

College of Computer Studies

60

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

*************************************************************/

import java.applet.*; import java.awt.*;

public class Widgets extends Applet { private Label nameLabel, addressLabel, messageLabel; private TextField name, address; private TextArea message; private Button button;

public void init() { setLayout(null);

// Create three Labels, named "Name", "Address" and "Message". nameLabel = new Label("Name"); addressLabel = new Label("Address"); messageLabel = new Label("Message");

// Create TextFields to enter the name and address. name = new TextField("Jean-Luc Picard");

College of Computer Studies

61

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

address = new TextField("Enterprise");

// Create a TextArea to enter a message. message = new TextArea("Resistance is Futile", 50, 50);

// Create a Button. This button does nothing useful when clicked. button = new Button("Submit");

// Position the widgets nameLabel.setLocation(0, 0); nameLabel.setSize(40, 20); addressLabel.setLocation(0, 20); addressLabel.setSize(70, 20); messageLabel.setLocation(0, 40); messageLabel.setSize(70, 20);

name.setLocation(100, 0); name.setSize(220, 20); address.setLocation(100, 20); address.setSize(220, 20); message.setLocation(100, 40); message.setSize(220, 100);

button.setLocation(110, 150); button.setSize(100, 20);

// Add the widgets to the applet add(nameLabel); add(name); add(addressLabel); add(address); add(messageLabel); add(message);

College of Computer Studies

62

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

add(button); } } What is Event-Driven Programming? Event-driven programming is called that because it involves writing programs that react to eventssuch as key presses, button clicks, mouse movements, and so on. The basic reality of this type of programming is that events are unpredictable. Steps to your approach: The following steps outline one approach to designing programs. 1. The most important step in programming is to design your program before you begin to code it. Starting to code a program before you have given thought to the design is certain to result in frustration. You should sketch your approach on paper before you begin to code. For many students, completing steps 2 through 5 below, then sketching the flow of the program is very helpful. 2. For any programming assignment, the first key is to understand the problem. Be sure that you know what problem your program is supposed to solve or what the program is supposed to do. 3. Define the output that your program is supposed to produce.

College of Computer Studies

63

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

4. Define what inputs are needed from the user in order for your program to produce the correct output. 5. After you know what the output is and what inputs the user must provide, you should be able to define what actions your program should perform on the user's inputs in order to produce the appropriate outputs. 6. Many beginning developers can complete steps 1 through 4 above without much problem. The next step, designing how the program will accept the inputs from user, process them, calculate the outputs and display the outputs to the user is where most students have problems. Sometimes students have problems identifying in which methods they should place to code to perform the various functions. You should draw a simple diagram or outline on paper before you begin to code. This diagram or outline should show in general terms, the methods that you are going to use, the variables required in each method and the actions that each method is going to perform There are some guidelines that you might find to be useful in making your diagram or outline. The first action that a program performs is usually to accept the inputs from the user. The actionPerformed method is commonly used to accept input from the user and store the user's inputs in variables. Sometimes, code can be placed in the actionPerformed method that tests the values of the user's input and determines which method to call based on the value of the user's input. Sometimes, the actionPerformed method

College of Computer Studies

64

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

simply accepts the users input and calls a different method, passing parameters to the called method to set the value of the called method's local variables. This method then tests the values of the users inputs if necessary are directs the flow of program. The strategy that is employed will be determined based on the nature of the programming assignment. In any event, the actionPerformed method is usually used to accept the inputs from the user, decide what action to take next and pass parameters to the method that it calls. The methods that process the user's input are usually created and given a name by the developer, with each method having a narrowly defined function. These methods usually use global variables and/or accept values for their local variables as parameters from the methods that call them. At some point, one of these methods usually calls the paint method, passing the appropriate parameters, in order to have the output displayed to the user. 7. The paint method is commonly used to display the output to the user. Sometimes calculations that are crucial to displaying the output correctly, such as the size of the applet, are placed in the paint method to cause the applet to display correctly. For example, if the output is dependent upon the size of the applet, the calculations needed to determine the size of the applet are placed in the paint method (or called from the paint method) because the paint method is automatically executed each time the applet is

College of Computer Studies

65

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

resized in the browser. Because the calculations necessary to display the applet are placed in the paint method the calculations will be performed each time the applet is resized. 8. In summary, as a beginning developer, you can usually design your code using an approach that uses the actionPerformed method to accept inputs from the user and direct the flow of execution to the appropriate method, passing the appropriate parameters to the called method. Any processing that needs to be done to the inputs can be handled by methods that your create and name yourself. The paint method should be called to handle displaying the output to the user.

Unit 3. Java Language Arithmetic Operators The following examples illustrate the integer arithmetic that can be done in Java, with different operators. For all these examples, assume x always has a value of 100 as given by the definition "int x = 100;":

College of Computer Studies

66

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008 Example x+5 x-5 x*2 x/2 x%2 Result 105 95 200 50 0

Operation Addition Subtraction Multiplication Division for Quotient Division for Remainder

Operator + * / %

The code written above in the example column represents what programmers call expressions. Programming languages can evaluate these expressions by looking up the value of any variable and performing the indicated operation. In reality these expressions are pretty useless if we dont do something with them like displaying them or storing them in memory or use them in some type of program instruction. Variables - One More Time We had seen variables earlier. Here is a small recap of that. Variables are the "stuff" in a computer program that can change as the program runs -- things whose values can vary. Each variable has a name, is of a particular type, and has a scope. Each type specifies what kind and range of values are permitted, and the size of the variable. For example, for an integer type the size is 32 bits in Java, and it can hold only integers in the range of values between -2 31 to 231 -1, i.e. from -2147483648 to 2147483647. The scope of a variable is that portion of your code where the variable may be used. For example, an instance variable declared in a class has a class scope: it can be used from the place it is declared

College of Computer Studies

67

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

till the end of the closing curly-braces of the class body. As opposed to the instance variables, there are local variables whose scope is limited to a block of statements within which the local variable is declared. You will encounter local variables most often in methods. Note that a method also contains a block of statements that make up the body of the method. Outside of the block of statements where it is declared, there is no life for that local variable. A Simple Example A simple example is given below that shows how to draw two circles where the radius of the circle is twice that of the other. /** * We need to draw two concentric circles, the bigger circle having a * that is twice that of the smaller circle. * Also, the bigger circle should touch the left and upper edge * of the applet. We try with diameter 50, and find out that it * is easier if we did not have to calculate by hand the radius if we * had relative values for the radius as shown in the second method. */ radius

import java.awt.*; import java.applet.*;

College of Computer Studies

68

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

public class Circles extends Applet { public void paint(Graphics g) { drawAbsoluteCircles(g); drawRelativeCircles(g); }

// Specify absolute values for the two circles public void drawAbsoluteCircles(Graphics g) { g.drawOval(0, 0, 200, 200); g.drawOval(50, 50, 100, 100); }

// Specify relative values for the two circles. public void drawRelativeCircles(Graphics g) { int r = 50;

g.drawOval(0, 0, 4 * r, 4 * r); g.drawOval(r, r, 2*r, 2*r);

College of Computer Studies

69

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

} } Using Arithmetic We had previously looked at the Pie example. As we look at it now, we are looking at the Pie straight on, as if it were a STOP sign on a pole at the corner of a street. By typing the number 80 into the box provided below and pressing the Go button, you can make the Pie look as if it has been blown down onto the ground. Try it now:

type in 80 press Go

Try entering some other numberssay, 30, 50, and 70pressing Go after each. Do you see that bigger and bigger numbers cause the Pie to tilt further and further back, as if the wind is blowing harder and harder? Entering a 0 leaves the Pie perfectly upright, and entering a 90 lays it down so flat that we can't see it at all!

College of Computer Studies

70

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

We are using arithmetic to rotate the Pie. We will only use numbers from 0 through 90. Enter a 0 and press Go. Now we are looking at the Pie head on. Imagine a horizontal line that passes through the middle of the Pie from left to right, just grazing the bottom of the left black wedge and just grazing the top of the right black wedge. Now imagine that the line is a stiff rod and that the Pie is attached to the rod with brackets so that the Pie can spin around the rod freely. As we enter a number and press Go, we are rotating the Pie by that number of degrees. When you type 30 and press Go, you are pushing the top of the Pie back 30 degrees. Type 66 and press Go, and you rotate the Pie 2/3 of the way toward laying flat. Type 90 and press Go, and, as we have seen, you can't even see the Pie at all. We are indeed using arithmetic to make the Applet interesting. This is done by calling the built-in Math methods round and cos. It is not important for this course that you understand the mathematics. What is important is that you understand that mathematical functions are implemented as methods in Java and that you as a programmer can call them whenever you need them. If you are interested in the details of this example, you can see how we achieved the rotate effect by studying the following Pie Applet code carefully. In particular, you will see that we have given the method drawPie parameters and code to accommodate drawing a rotated Pie. Secondly, you will notice that a method, drawPieSlanted, has been created that performs the necessary mathematical calculations before making the call to drawPie. import java.awt.*; import java.awt.event.*;

College of Computer Studies

71

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

import java.applet.*;

public class Pie extends Applet implements ActionListener { public int slope; public Button go; public TextField in;

public void init() { slope = 0;

go = new Button("Go"); in = new TextField(5);

add(in); add(go);

go.addActionListener(this); }

public void drawPie(Graphics g, int x, int y, int width, int height, int angle) {

College of Computer Studies

72

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// the width of the outer edge int bandWidth = width/7; int bandHeight = height/7;

// the dimensions of the slices int propWidth = width - 2*bandWidth; int propHeight = height - 2*bandHeight;

// draw the edge g.setColor(Color.red); g.fillOval(x , y, width, height);

// the yellow slices g.setColor(Color.yellow); g.fillArc(x + bandWidth, y + bandHeight, propWidth, propHeight, angle, 90); g.fillArc(x + bandWidth, y + bandHeight, propWidth, propHeight, angle + 180, 90);

// the black slices g.setColor(Color.black); g.fillArc(x + bandWidth, y + bandHeight, propWidth, propHeight, angle + 90, 90);

College of Computer Studies

73

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

g.fillArc(x + bandWidth, y + bandHeight, propWidth, propHeight, angle + 270, 90); }

public void drawPieSlanted(Graphics g, int x, int y, int size, int angle, int slope) { int cos = (int)Math.round((size/2) *

Math.cos(slope*Math.PI/180)); drawPie(g, x, y + (size/2) - cos, size, 2 * cos, angle); }

public void paint(Graphics g) { drawPieSlanted(g, 20, 20, 70, 0, slope); }

public void actionPerformed(ActionEvent e) { slope = Integer.parseInt(in.getText()); repaint(); } }

College of Computer Studies

74

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Finally While some people view this stuff as somewhat simple and possibly a waste of time, it turns out that being crafty with this stuff can allow us to solve some very interesting problems. We will pose some of those problems for you in the coming weeks so be sure you understand this stuff. If you are unclear any of it, reread the book and work slowly through the examples. It will make things clearer -- remember those scales. Boolean Operators You typically use Boolean operators when you have two or more Boolean expressions and you want to combine them to get a new Boolean expression. There are many examples of Boolean operators and expressions in the real world. For this course you need to know only about the following operators.

Operator AND OR NOT AND Operator

Symbol && || !

The Boolean AND expression evaluates to true only when both the component Boolean expressions evaluate to true. Example: If your height is five feet or higher, AND you can run the 100 meters race in 11 seconds or under, you can join the police force. Here, the following two Boolean expressions are combined to yield a third expression:
College of Computer Studies

75

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

1. Is height greater than or equal to 5 feet? 2. Is your timing on the 100 meters race 11 seconds or under? Only when both of the above Boolean expressions are true, will the whole Boolean expression be true. You can join the police force only when the whole Boolean expression is true. OR Operator A Boolean OR expression evaluates to true only when either or both of the component Boolean expressions evaluate to true. Here is an example of a Boolean OR: If it is raining or snowing outside, you cannot play. There are two Boolean expressions which are joined together by an OR operator to form a third Boolean expression: 1. Is it raining? 2. Is it snowing? If either of them evaluates to true, the whole Boolean expression evaluates to true. When the whole Boolean expression evaluates to true, you cannot play outside. NOT Operator Here is an example of a NOT operator: If your height is NOT greater than or equal to five feet you cannot join the police force.

College of Computer Studies

76

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Complex Boolean Operators Here are some examples of complex Boolean operators:

If the reservoir is NOT empty AND the water heater is working, you can take a hot shower.

If the temperature is hotter than 95 degrees Fahrenheit OR lesser than 60 degrees Fahrenheit AND you do not have air conditioning AND heater, it will get pretty uncomfortable.

Boolean Type and Boolean Variables Boolean is a type just like int and double. Just like you can have variables of type int and double, you can also have variables of type boolean. Boolean variables can take only one of two values: true or false. Since a Boolean expression evaluates to a Boolean value, you can assign any Boolean expression to a Boolean variable. In the example below, we make use of Boolean variables. The following table illustrates the result of the three Boolean operators when two Boolean variables take on different values.

a true true false false

b true false true false

a && b true false false false

a || b true true true false

!a false false true true

College of Computer Studies

77

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Rules of Evaluating a Boolean Operator Notice that the Boolean operator && (AND) and || (OR) require two operands, while the ! (NOT) operator requires only one operand. When you use the Boolean AND operator, and the first operand evaluates to false, the second operand is never evaluated. Irrespective of the value of the second operand, the AND expression will evaluate to false. Let us take our previous example: "If your height is five feet or higher, AND you can run the 100 meters race in 11 seconds, you can join the police force." When the first condition, height is five feet, or higher evaluates to false, there is no need to evaluate the second condition. You cannot join the police force. Similarly, for the OR operator, the second operand is not evaluated when the first operand evaluates to true. Let us consider our previous example: If it is raining or snowing outside, you cannot play. When the first condition: "Is it raining outside" evaluates to true, there is no need to check for the second condition. You cannot play. Example Below, you will see an applet that performs Boolean operations. It displays six text fields. On the three text fields on the left, type in the names of three friends. On the three text fields on the right, type in their age in years (as an integer), and click the button. It should display the results of various Boolean operators. If you

College of Computer Studies

78

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

do not type in integers on the three text fields on the right, you will not see anything happening. Try to run this in the Applet Viewer.

/***************************************************************** * Sample class * SSD1 -> Intro to Java -> Java Fundamentals -> Boolean Operators & Expr * Example for Boolean operations, arithmetic operations * and getting input from user *****************************************************************/

import java.awt.*; 79

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

import java.applet.*; import java.awt.event.*;

public class Booleans extends Applet implements ActionListener { public TextField name1, name2, name3; public TextField ageField1, ageField2, ageField3; public Label names, ages; public TextArea display; public Button go;

public void init( ) { Panel p1, p2, p3; setLayout(new GridLayout(3, 1, 10, 10));

p1 = new Panel(new GridLayout(1, 2, 10, 10)); p2 = new Panel(new GridLayout(4, 1, 5, 5)); p3 = new Panel(new GridLayout(4, 1, 5, 5));

names = new Label("Names"); p2.add(names); ages = new Label("Ages"); p3.add(ages);

College of Computer Studies

80

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

name1 = new TextField(); p2.add(name1); ageField1 = new TextField(); p3.add(ageField1);

name2 = new TextField(); p2.add(name2); ageField2 = new TextField(); p3.add(ageField2);

name3 = new TextField(); p2.add(name3); ageField3 = new TextField(); p3.add(ageField3);

p1.add(p2); p1.add(p3); add(p1);

go = new Button("Go"); add(go);

display = new TextArea(); display.setEditable(false); add(display);

go.addActionListener(this); }

public void actionPerformed(ActionEvent e) { int age1, age2, age3;

College of Computer Studies

81

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

String s1, s2, s3, out; Graphics g = getGraphics(); boolean b1, b2, b3, b4, b5, b6;

age1 = Integer.parseInt(ageField1.getText()); s1 = name1.getText(); age2 = Integer.parseInt(ageField2.getText()); s2 = name2.getText(); age3 = Integer.parseInt(ageField3.getText()); s3 = name3.getText();

// clear the printing area; g.clearRect(10, 280, 500, 200);

// Is s1 older than s2? I.e., is age1 greater than age2? b1 = age1 > age2; out = "\"" + s1 + " is older than " + s2 + "\" is " + b1 + "\n";

// Is s2 not older than s3? I.e., is age2 not greater than age3? b2 = ! (age2 > age3); out = out + "\"" + s2 + " is NOT older than " + s3 + "\" is " + b2 + "\n";

// Is s1 and s3 of the same age? I.e., is age1 equal to age3? b3 = age1 == age3; out = out + "\"" + s1 + " and " + s3 + " are of same age\" is "

College of Computer Studies

82

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

+ b3 + "\n";

// Is s2 younger than s3 but older than s1? // I.e., Is age2 lesser than age3 AND age2 greater than age1? b4 = ((age2 < age3)&&(age2 > age1)); out = out + "\"" + s2 + " is younger than " + s3 + " but older than " + s1 + "\" is " + b4 + "\n";

// Is s1 not the youngest? // I.e., is age1 greater than or equal to age2 // OR age1 greater than or equal to age3? b5 = ((age1 >= age2) || (age1 >= age3)); out = out + "\"" + s1 + " is not the youngest\" is " + b5 + "\n";

// Is s2 the youngest? // I.e., is age2 less than age1 AND age2 less than age3? b6 = ((age2 < age1) && (age2 < age3)); out = out + "\"" + s2 + " is the youngest\" is " + b6 + "\n";

display.setText(out); } }

College of Computer Studies

83

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Sequential Execution and Control Structures A computer executes statements sequentially in the order in which the statements are written. Many times we may need to control the order of execution to be different from the order in which the statements are written. To facilitate the programmer to control the order of executions, there are many options available in most of the programming languages, and are collectively called control structures. if-else Statement Control structures are best illustrated by flowcharts. A flowchart is a graphical representation of the order in which statements are executed. Flowcharts are drawn with various symbols such as diamonds, rectangles, circles, etc. A diamond is used when a test is to be done to decide which way to proceed. A rectangle is used to denote sequential execution of statements in that rectangle. These symbols are connected by lines with arrows called flow-lines. Execution proceeds in the direction of the arrow. A circle is used as a junction point where multiple flow-lines meet. A flow-chart of an if-else statement is given below.

College of Computer Studies

84

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

The syntax of an if-else statement is: if (booleanExpression) statement

else statement In the above, the statement can be a single statement, a block of statements (enclosed by curly braces) or a null statement (just a semicolon). Thus, all three of the following are valid:
if if if

( isRaining ) canPlay = false; // A single statement

( isRaining ); // Null statement. Does nothing. ( isRaining ) {

canPlay = false;

College of Computer Studies

85

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON }

AMA Computer University

1ST trimester, SY 2007-2008

takeUmbrella = true;

// block of statements

If there is no else-clause, the flowchart would look like the following:

A simple example of checking conditions using the if statement is given below along with the code.

/**************** * Example of Conditional Statement * * Prints different message on the screen, * depending on how many times the applet * needed repaint. Try resizing the applet * or reloading your page more than 3 times to change

College of Computer Studies

86

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

* the message. ****************/

import java.applet.*; import java.awt.*;

public class CondSampleApplet extends Applet { private int count = 1;

public void paint(Graphics g) { if (count < 3) g.drawString("Paint was called fewer than 3 times.", 20, 20); else g.drawString("Paint was called " + count + " times.", 20, 20); count = count + 1; } } Nested if Statements

College of Computer Studies

87

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Sometimes you may need a multi-way if-statement. For example, if the value of a light is red, then Stop, else if value of light is green then Go, else if the value of light is BlinkingYellow then Proceed With Caution, else if the value of light is blinking-red then Stop and Go. For these situations, you can use a nested-if statement as mentioned in page 102 of your book

Naughton/Schildt. You can also see an example of nested if statement in the next example towards the end of the actionPerformed method. Below is another applet that uses these control structures that are new to this module as well as the arithmetic and Boolean expressions introduced earlier. Take a careful look at this applet: This applet is a simple calculator. Notice that whenever you have more than one button in your GUI, you will find the need to use an if statement. Only with an if statement can you find out which button was clicked. Only after you find out which was clicked, can you take appropriate action to respond to the click.

import java.awt.*; import java.awt.event.*;

College of Computer Studies

88

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

import java.applet.*;

public class Calculator2000 extends Applet implements ActionListener { public TextField in1, in2, out; public Button plus, minus, times, div;

public void init() { Panel p1, p2; setLayout(new GridLayout(2, 1, 10, 10));

in1 = new TextField(); in2 = new TextField(); out = new TextField(); out.setEditable(false); p1 = new Panel(new GridLayout(4, 1, 2, 2)); p1.add(in1); p1.add(in2); p1.add(out); add(p1);

plus = new Button("plus"); minus = new Button("minus"); times = new Button("times"); div = new Button("divide"); p2 = new Panel(new GridLayout(1, 5, 10, 10)); p2.add(plus); p2.add(minus); p2.add(times); p2.add(div); add(p2);

College of Computer Studies

89

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

plus.addActionListener(this); minus.addActionListener(this); times.addActionListener(this); div.addActionListener(this); }

public void actionPerformed(ActionEvent e) { String ac = e.getActionCommand(); double x1 = new Double(in1.getText()).doubleValue(); double x2 = new Double(in2.getText()).doubleValue(); double result = 0;

if (ac.equals("plus")) result = x1 + x2; else if (ac.equals("minus")) result = x1 - x2; else if (ac.equals("times")) result = x1 * x2; else if (ac.equals("divide")) result = x1 / x2; out.setText(result + ""); } } Previously, we had talked about some arithmetic and Boolean expressions. Then we got into control. All of that comes together in the actionPerformed method above. Notice that we use the equals method of the String class in the actionPerformed method. The equals method of a string checks if the

College of Computer Studies

90

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

string on which it is called is equal to the string that is passed in as a parameter. It returns the result of the comparison as a Boolean value. Take a good look at this Web page one or two more times. Walk though the code. Copy the applet into a file and run it. Modify it and try different things. There are some important concepts here. Their use in a practical applet may not yet be apparent but we hope to change that. Do not go on until this begins to make some sense to you. The Need for Iteration We have worked through some interesting programming problems. Thus far we have seen two "forms" of code execution in our programs. We started with a style of execution that is called sequential execution. Sequential execution means that all of the statements in our programs are executed one after another, starting at the top and moving in sequence down to the bottom of the list of statements. No statements are skipped, and none are executed more than one time. Therefore, if we are working with a specific methodsay, the Graphics method fillOvaland we want to draw 37 circles, we have to call that method 37 times. Later we worked with what we call control structures, which allow selective executionthat is, they allow execution to select different paths (or branches) through our Java statements, and we explored and used the if statement and the if/else statement. (Note that some authors consider these statements the same

College of Computer Studies

91

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

control structure, and other authors consider them two different control statementsit does not really matter to Java as long as you use them correctly.). The if statement allows our program to evaluate a condition or set of conditions to determine if they are true or false. If the condition or conditions are true, then a series of statements is executed. If the condition or conditions are false, the series of statements is skipped. The if/else statement is similarif the condition or conditions evaluate to true, statements are executedjust as with the if statementbut if they are false, execution passes to the alternative statement or series of statements that follow the keyword else. You may want to refer back to the course page titled "Simple Control Structures" for examples of code that use if and if/else statements. You may also wish to review pages 100-3 in the Schildt textbook. So we have seen two forms of execution; sequential and selective. This module introduces you to the last form of executioniteration or repetitive execution. The shortcoming of selective execution is that it does not allow us to repeat similar tasks easily. Those 37 circles will still require 37 statements, even if we are very clever with one of the control structures. Iteration, on the other hand, allows the program to repeat statements until some condition is met. You will learn in the next module that Java offers three forms of iteration for the programmer to use (although that module covers only two of those forms in

College of Computer Studies

92

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

detail). With these forms of iteration or loops, we as programmers can create applications that repeat one or more Java statements as required. This adds tremendously to our array of tools. These iteration tools are very powerful. However, with their power comes the opportunity to make some very serious errors. And these errors are not always easy to test for or find. Alas... we are getting ahead of ourselves. Let's explore loops, design a few of them, and then talk about loop errors and debugging. This is where you should (if you have not already) really begin to have some fun. Java Loops In this page we will look at two types of Java loops: while loops and for loops. Java has a third type, do loops; however, for our purposes the first two types will be sufficient. All of these loop types do essentially the same thingthat is, they start and continue iterations of a set of instructions as long as the Boolean expressions that control them (the loops) evaluate to True, and once the expressions evaluate to False, the loops "terminate" and the iterations cease. However, although these loop types do essentially the same thing, having a variety of types to choose from allows us to choose among options when writing code for particular tasks. It is desirable, and usually possible, to make the structure of your program match the intent of your program. State your solution out loud in the form of a while loop then in the form of a for loop to determine which best fits the problem you are solving.

College of Computer Studies

93

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

The while loop

Form

of

a Diagrammatic representation of how the loop is executed by the computer.

while loop while guard expression) (loop

loopBody // the stuff to iterate Here is a simple example of this loop and the output generated by the loop (assume that these statements are in the paint method). int i, yLoc;

i = 1;

yLoc = 25;

while (i < 5)

College of Computer Studies

94

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

g.drawString("value of i is " + i, 25, yLoc);

i = i+1;

yLoc = yLoc + 15;

} The output would be: value of i is 1

value of i is 2

value of i is 3

value of i is 4 The local variable yLoc is used to move each subsequent drawString down the screen. The first string will be 25 pixels down from the top edge. The second one will be 40 (= 25 + 15) pixels down. The third one will be 55 pixels.... Without this increment of the variable yLoc, each drawString would be drawn on top of the previous one, creating a visual mess. The code within the parentheses of the loop:

College of Computer Studies

95

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

(i<5) is the loop guard. This is the expression that is evaluated to see if the loop continues to iterate or stops. If this expression is true, the loop continues the iteration. If this expression is false the loop terminates iteration and execution continues with the statement that follows the loop. The guard can be any reasonable Boolean expression. It fact, MUST be a Boolean expression. The while loop follows the "test then execute" pattern; it tests the value of i before printing it. The test is "i less than 5" so when i is equal to 5 the result of the test is false and i is not printed when its value is 5. We will return to a slightly different form of this code in our discussion on debugging loops. The use of loops can introduce some very subtle errors in our code. The Loop Body The loop body can be one of the following:

an empty statement. You will see more about empty statements in the discussion of for loops below. An empty statement is denoted by a simple semicolon (";").

a single statement. You typically write loops with single statements when you want the program to "sleep" for sometime. You will see the need to "sleep" the program in animations. In animation, you might want to visually move an object from one place on the screen to another. Computers execute statements at blazing speeds. Hence the execution of statements 96

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

that move an object from one location to another may be so fast, that the movement may not be visible to the human eye. In such cases, you want to slow it down by sleeping the program for every intervening step in the movement. Here is an example of a loop with a single statement to simulate a "sleep":

while (i < 1000)

i = i+ 1;

a block of statements. This is the most common loop body. When you have a number of statements that need to be executed for every iteration of the loop, you put all of those statements in a block. The code within the pair of curly braces "{ }" in the above example is the loop bodythis is the code that is looped or iterated. You do not need a pair of braces if you are iterating only one statement. However, we strongly advise you always to use a pair of braces to reduce the chance of errorserrors that are not found by the compiler and that are very difficult to locate and fix! An empty while statement should not have curly braces.

Here is the code sample from above: int i, yLoc;

i = 1;

College of Computer Studies

97

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

yLoc = 25;

while (i < 5)

g.drawString("value of i is " + i, 25, yLoc);

i = i+1;

yLoc = yLoc + 15;

} What happens if we leave out the i = i+1; statement like this? int i, yLoc;

i = 1;

yLoc = 25;

while (i < 5)

College of Computer Studies

98

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

g.drawString("value of i is " + i, 25, yLoc);

yLoc = yLoc + 15;

} What would be the output for this new code? Think about this... We set i equal to 1 and then make the test "i less than 5" which is true. We then print the value of i which is 1. Since the inside of the loop is done we go back to the test. Since i is still 1 it is less than 5 so the test is true and we execute the print statement printing 1. Since the inside of the loop is done we go back to the test. Since i is still 1 it is less than 5 so the test is true and we execute the print statement print 1. There seems to be a pattern herean infinite patternthis is an infinite loop and it will print the number 1 forever or until you terminate the program or turn off the computer. The output would start like this: value of i is 1

College of Computer Studies

99

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

value of i is 1

value of i is 1

value of i is 1

... ... to infinity ... The for Loop Another loop in Java is the for loop. It is true that you can do anything with a for loop that you can do with a while or do-while loop. While you can play a game of golf with only a putter, you can play a better game of golf with a bag of clubs. Similarly, you can write better programs if you use all three loops. It turns out that if you understand one loop and can use it correctly, it is fairly straightforward to learn to use the other two.

Diagrammatic representation of how the Form of a for loop loop is executed by the computer.

College of Computer Studies

100

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

for

(initialization;

loopGuard; update)

loopBody

In the initialization part, you typically initialize the loop variable. In the example below, the loop variable i is initialized to 0. After initialization, the loopGuard is evaluated. loopGuard is a Boolean expression. It should evaluate to true or false. If the loopGuard evaluates to false, the loop is terminated. After evaluating the loopGuard, and when it evaluates to true, the loopBody is executed. Then, the update is executed. In the example below, the update increments i by 1. After the update, it is on to the cycle of loopGuard - loopBody - update - loopGuard The for loop also requires a Boolean expression to be true to continue its iteration, but its syntax is more involved. Here is a for loop that does some counting: int i;

College of Computer Studies

101

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

for (i = 0; i < 5; i = i+1)

g.drawString("value of i is " + i, 25, yLoc);

yLoc = yLoc + 15;

} The output for this is:

value of i is 0

value of i is 1

value of i is 2

value of i is 3

value of i is 4 To examine the for loop structure, let's write it in a slightly different format:

College of Computer Studies

102

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

the keyword "for" is part of Javait tells Java that a loop is for ( i = 0; first and only one time this is the Boolean testit happens second and is repeated i < 5; one time for each iteration this is the update of control variable i (is typically an i i+1; ) one time for each iteration the closing parenthesis is required by Java the opening brace begins the body of the loopthe next two statements make up the loop body and happens third and is repeated once for each iteration {

present the opening parenthesis is required by Java this is the initialization of the control variable, iit happens

= increment or decrement)it happens fourth and is repeated

g.drawString("value of i is " + i, 25, yLoc); yLoc = yLoc + 15;

the closing braces ends the body of the loop

The pattern of execution for the for loop is shown below for(

#1 i = 0;

#2 i < 5;

College of Computer Studies

103

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

#4 i = i + 1)

#3 g.drawString("value of i is " + i, 25, yLoc);

#3 yLoc = yLoc + 15;

} #5 would be the next instruction. The order of execution is: #1-> #2 -> if #2 is true -> #3 -> #4 -> #2

if #2 is true -> #3 -> #4 -> #2

if #2 is true -> #3 -> #4 -> #2

if #2 is false -> #5 This continues until #2 is false. Once #2 is false, execution drops to the next instruction in the program marked above as #5.

College of Computer Studies

104

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

A loop body can also contain an empty statement. As in the while loop, the loopBody can be an empty statement, a single statement or a block of statements. We mentioned earlier that you might feel the need to "sleep" the program (i.e., slow down the execution of the program) while animating some drawing. It is possible to sleep with empty statements in the loopBody of the for loop: for (i = 0; i < 1000; i = i+1); Notice that the loop body does nothing because of the empty statement. Hence, the loop counts from 0 to 1000 and then the loop is done. An example of a for loop with one statement is given below. Notice that the loopBody is an if statement. System.out.println ("Here are the even numbers between 1 and 10:");

for (i = 1; i < 10; i= i+1)

if (i % 2 == 0)

System.out.println(i);

College of Computer Studies

105

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

This is the conclusion of our look at the syntax of loops and the patterns of execution of loops. Before you continue to the next section, we strongly advise you to reread your text and this Web page to clear up anything you do not understand. The use of loops opens many possibilities to us as programmers, and we can make our programs more interesting to our users. However, we as programmers must understand a great deal about loops to use them successfully. That understanding begins with this material as well as the material on Boolean expressions. Do not hesitate to review the previous material. It will make the subsequent material easier to understand. Suggested Exercises 1. Write an applet which has a TextField, takes an integer n and writes all the integers from 1 to n. Have a TextArea in the applet also, in which you will display the results, as shown in the applet below. 1. What has to be true of n for at least one number to be printed? Beware of infinite loops. 2. For what values of n might your loop be infinite? 3. How do you guard against an infinite loop?

College of Computer Studies

106

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

2. Write an applet that does the same as the previous one, just that the printing is done in the reverse order.

3. A sequence of numbers is printed in the following way. It starts with 1, and every number p in the sequence determines its successor in the following way: if p is odd, its successor is 2 * p; if p is even, its successor is 3 * p + 1. Make an applet that takes a positive integer and prints this sequence until the numbers exceed n. For example, for p = 100, the printed part of the sequence is 1, 2, 7, 14, 43, 86.

3.2.3 Designing a Loop


First Loop Problem Code Dissection How Do You "Know What to Put in These Parts?" A Second Loop Problem Suggested Exercise

We mentioned that there are three types of loops in Java: the for loop, the while loop, and the do loop. However, you have been introduced to the syntax and execution patterns of only two of these loops: the for loop and the while loop. In this section we will walk through the process of designing two applets that use loops to accomplish two different tasks. We will use the for loop for all of this work, but the thinking we apply here in our use of the for loop can be applied to

College of Computer Studies

107

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

the while and the do loops as well. The reason that we are going to work exclusively with the for loop is that doing so will help you develop a reasonable understanding of using that type of loopan understanding that, again, can be applied to the other two loops. In fact, you must work with the other two loops as part of your practice working with Java loops. As we mentioned above, we are now going to design two applets that use loops:

an applet that computes and displays the squares of all numbers between two values input by the user

an applet that draws a series of circles across the screen

First Loop Problem Let's begin with the loop that computes and displays the squares. Let's assume that we have written an applet that has two TextFields that allow the user to enter a starting integer and ending integer. Our code checks to insure that the starting integer is less than the ending integer. If that is true, we call a method, printSquares, that prints the number and its square. Note that the output can appear below the applet windowwe do not protect against that possibility. /***************************************************

* Test Applet for practice

* SSD1 -> Java Language -> Loops -> Designing a loop 108

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

***************************************************/

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class SquaredNumbers extends Applet implements ActionListener

public Button bSquare;

public TextField startNumInput, endNumInput;

public Label title;

public int startNum, endNum;

College of Computer Studies

109

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

public int mode;

public void init( )

title = new Label("THE SQUARE MACHINE");

bSquare = new Button("COMPUTE SQUARES");

startNumInput = new TextField(8);

endNumInput = new TextField(8);

add(title); add(bSquare);

add(startNumInput);

add(endNumInput);

College of Computer Studies

110

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

bSquare.addActionListener(this);

startNum = 0; endNum = 0; mode = 0;

public void paint(Graphics g)

if (mode == 0)

g.drawString("Enter starting and ending values and press the button",

10, 150);

else if (mode == 1)

g.drawString("Input is invalid -- check and renter", 10, 150);

else

College of Computer Studies

111

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

printSquares(g, startNum, endNum);

public void actionPerformed(ActionEvent e)

startNum = Integer.parseInt(startNumInput.getText());

endNum = Integer.parseInt(endNumInput.getText());

showStatus("Button Pushed");

if (startNum <= endNum) mode = 2; else mode = 1;

repaint();

College of Computer Studies

112

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// Here is the code that prints the squares of the entered numbers --

// this contains the loop

void printSquares(Graphics g, int num1, int num2)

int i, yLoc;

g.setColor(Color.yellow);

g.fillRect(0, 0, getSize().width, getSize().height);

g.setColor(Color.black);

yLoc = 65;

for (i = num1; i <= num2; i = i + 1)

College of Computer Studies

113

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

g.drawString("The square of " + i + " is " + i * i, 25, yLoc);

yLoc = yLoc + 15;

Code Dissection The method below has a loop that prints squares. It may or may not be easy for you at this time to see how the loop works, so let's walk through the execution of the code and then discuss how we developed this loop. For the walk through, let's go through the code below carefully and look at it line by line. for (i = num1; i <= num2; i = i+1)

g.drawString("The square of " + i + " is " + i * i, 25, yLoc);

yLoc = yLoc + 15; 114

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

} Let's start with the first line: for (i = num1; i <= num2; i = i+1) A for loop's first line should have three elements: an initialization, a test (or guard), and an increment (or update). Does this line have those three required elements?

Is the initialization there? i = num1; Is the test or guard there? i <= num2; Is the increment or update i = i+1 there? The answer is, "Yes, they are there." Now we will look at the loop's body. The body of a loop is where the "work" gets donethat is, the body is where the statements that carry out the tasks are located. Are all the necessary statements present in the loop body?

Is the value of i drawn? g.drawString("The square of " + i Is the value of the square of i drawn? " is " + i * i, Is the value of the y location incremented for the next line of yLoc = yLoc + 15; output?

College of Computer Studies

115

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

So, it looks like all of the needed elements are in the loop. If you did not follow this walk-through, return to the previous course module and review the for loop's syntax. How Do You "Know What to Put in These Parts?" This is a tough question to answer. We can help you two ways. 1. We can give you a pattern to follow that will help you organize your thoughts. 2. We can show you some loops that do different things and start the beginnings of a "loop history" for you. The bottom line is that you will learn how to write loops by looking at examples and writing your own. Looking at examples is like listening to someone play the flute. Writing your own loops is like actually playing the flute yourself. Which one of these, listening or playing, better helps a flute player become a better player? Who knows? But the best way to learn how to write loops consists of looking at loops written by others and writing loops of your own. How do we know what to put in a loop? We recommend this five step process: 1. Identify what must be true when the loop is done. 2. Use the reverse or negation of this condition for the loop guard. 3. Initialize things so the loop will begin correctly.

College of Computer Studies

116

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

4. Increment or update the appropriate variable so that the loop will eventually stop. 5. Put the code that is to be iterated within the loop body. Now, let's look at our example from the perspective of the 5-step process outlined above: 1. Identify what must be true when the loop is done. The user is giving us two valuesa starting value and an ending value. The actionPerformed method is insuring that either the values are equal or the starting value is less than the ending value. If we initialize the variable i by assigning it the value of the starting value and then increment i by 1 each time the loop iterates, then when the loop stops, we want the value of i to be equal to the value of the ending value. The short answer is that "i must be equal to the ending value." 2. Use the reverse or negation of this condition for the loop guard. If i must be equal to the ending value when the loop stops, the opposite is "not equal to." However, we going to be a little "permissive" and allow the user to enter the same the value for both the starting and ending values. That is, we are not going to follow the reverse-or-negation rule strictly. However, this also means that when the user does enter the same value in both fields, the applet

College of Computer Studies

117

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

will display only one line of outputbut that is okay. So if, on the other hand, we are not permissive and instead test that i is not equal to (the != operator ) the ending value, the user cannot enter the same value in both fields. Think about this before you go on. If the user enters the same value in both fields (the value 10 for example), then i will be set to 10 (the starting value), and the test i ! = num2 will be false, since the ending value is also 10. To allow the user to enter the same value in both starting and ending value fields, we construct the test using the less-than-orequal operator, which is <=. In the above example, if the starting and ending values are 10, then when i is set equal to the value of the starting value, the test i <= num2 (where num2 holds the ending value) will be true, since 10 is less than or equal to 10. So our negation will be "i will be less than or equal to the ending value." Notice that this walk through took up a lot of text. This is the part that usually requires the most thinking when a loop is being planned. 3. Initialize things so the loop will begin correctly.

College of Computer Studies

118

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

We assign the value of the starting value to the variable i, so that should work. If we do not do this, then the variable i may have a value of 0 or a value left over from a previous set of iterations. We also have to set the value of yLoc to a valid value so that the output will fit on the screen. We could do this in the init method, but subsequent input from the user will drive the output below the window. So in this code, we have initialized the value of yLoc before entering the loopbut we could have done this in the loop like so: for (i = num1, yLoc = 45; i <= num2; i = i+1) Notice that we can put multiple initializations in the first part of the for loopBUT also notice that we use a comma to separate them!!! 4. Increment or update the appropriate variable so the loop will eventually stop. We must increment the value of i to insure the loop stops. That is done in the third part of the first line of the for loop where we see the code i = i+1 This is the part of the loop that insures that the value of i will eventually reach and exceed the stopping value. If we leave this out, the loop will iterate infinitely. 119

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

There is one other increment we must do to get the correct output we must change the variable yLoc to keep the output from being printed on top of the previous line of output. In the example above we do that in the loop body as a single statement, but we could have done it in the first line of the for loop, just as we initialized it, like this: i = i+1, yLoc = yLoc + 15 Notice again that a comma is used to separate the two statements. 5. Put the code that is to be iterated within the loop body. In the original example, two lines of code are iterated: g.drawString("The square of " + i + " is " + i * i, 25, yLoc);

yLoc = yLoc + 15; If we had elected to increment the yLoc variable in the first line of the for loop, then we only would have needed to put the g.drawString(...) in the body of the loop This 5-step process is a reasonable pattern to follow as you write loops in the remainder of this course. With more complex problems, it is still a good way to begin to think about how to build the loop.

College of Computer Studies

120

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

A Second Loop Problem Let's apply this thinking to our second problemwe want to draw a series of 10 circles across the middle of the applet window. We want to avoid drawing partial circles, yet we still want the circles close to the left and right edges. How can we do this? Let's first figure out what we know.

We know the width of the window by using getSize().width. We know the height of the window by using the getSize().height. We know that we want 10 circles, so the size of each circle can be the width of the window divided by 10.

Okay, it looks like we know enough to solve this problem. But first we need to calculate the size of the circlewith something like int size = getSize().width / 10; This will give us an integer with a remainder between 0 and 9. Now where do we draw the circle? If we start at 0 on the left edge of the window and draw the first circle, we can move size number of pixels to the right and draw the next circle. This means that if we use the variable x, it will be initialized to 0 and incremented by size: for (x = 0; ??????? ; x = x + size)

College of Computer Studies

121

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

What is the guard or the Boolean test that goes where the ????? are shown in the above line? We have two answers. We can count to 10 using the variable i like this: for (i = 1, x = 0; i <= 10; i = i+1, x = x + size) We can initialize i and x in the first part of the for loop and increment i and x in the third part as shown above. This all we have to do is draw the circles in the body of the loop. Here is applet and the complete code that implements these ideas:

/***************************************************

* Test Applet for practice

* SSD1 -> Java Language -> Loops -> Designing a loop

***************************************************/

import java.awt.*;

import java.applet.*;

College of Computer Studies

122

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

import java.awt.event.*;

public class Circles extends Applet

public void paint(Graphics g)

int x, width, y, height, size, i;

width = getSize().width;

height = getSize().height;

y = height / 2; // this places the circles near the vertical

// center of the window

College of Computer Studies

123

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

size = width / 10; // determine the diameter of the circles

for (i = 1, x = 0; i <= 10; i = i+1, x = x + size)

g.setColor(Color.red);

g.fillOval(x, y, size, size);

g.setColor(Color.blue);

g.drawString("" + i, x , y );

College of Computer Studies

124

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

The above code determines the needed sizes and locations and then uses a loop to draw the 10 circles. You can copy this code into your demo applet and experiment with itsomething we always advise. Wait a Minute... Do we really need to count from 1 to 10 in the above loop? Think about it. Could we instead just draw circles until we run out of room? When we get to the loop, we already know the width of the window and the size of each circle. Could we write the loop test in a different way? What if we change the guard to look like this? for ( x = 0; x + size <= width; x = x + size)

g.setColor(Color.red);

g.fillOval(x, y, size, size);

} This works perfectly. The loop guard now tests the sum of the left edge of the circle plus its diameter against the width of the applet window. As long as the

College of Computer Studies

125

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

sum of the left edge of the circle plus its diameter is less than the width of the window, the circles are drawn. Notice, however, that we do lose our nice labels on each circle. Which way is the best way? The answer is that either way is perfectly okay. They are just two different ways to solve the same problem. One of the nice things about programming (in some people's opinion) is that there are often several good ways to solve the same problem. Suggested Exercise 1. In this exercise you will design and write an applet that draws the Indian flag on the screen. An image of the Indian flag is shown below. Below that image is an applet that draws the Indian flag. However, you don't have to make the picture ornatefor example, the wheel can be very simple.

College of Computer Studies

126

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Design: 1. Break the problem into two major activities. What are they? We suggest to first draw the rectangle for the flag and the three colored stripes. Then the second part would be to draw the spoked wheel in the center. 2. Is a loop appropriate for drawing the stripes? Why or why not? 3. A loop is definitely appropriate for drawing the spoked wheel. What pieces of information are necessary to do this? What is iterated? Hints: remember the Graphics methods fillArc and fillOval. And also remember that a circle has 360 degrees. 3.2.4 Testing a Loop Testing a loopwhat do we mean by testing a loop? Once we have written code and have removed all of the syntax errors, we always have to run it to "see if it is correct." If we are drawing a picture, we will want to make sure that the picture that is drawn is the picture we want. If we are computing a value, we will want to check to see if the value that is calculated is correct. When we start using loops, we must check to see if the output generated by the loop is correct. For example, to check example loop on the previous page (see "3.2.3 Designing a Loop"), we only had to 1. count the circles 2. look for partial circles on the left and right sides of the applet

College of Computer Studies

127

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Or was there something else...? The circles have to fit on any size applet, so we really should change the size of the applet to see if the circles are drawn correctly10 circles with no partial circles on the left or right edge. Question: How many times should we change the size of the applet to be sure the loop works correctly? Once, three times, fourteen times? One time for each pixel of width on the monitor screen? This last answer, "one time for each pixel of width on the monitor screen" is called exhaustive testing, but it would be possible only if we were sure that we had the widest monitor in existence. If someone has a monitor that is 23000 pixels wide, we are probably in trouble. It turns out that exhaustive testing is not always practical. In this case, exhaustive testing is not reasonableso what is? The answer to this question comes from experience with loopsthe more loops you write, the more insight into loop errors you will gain (due to all the mistakes you make with loopsthe author has, in fact, acquired a tremendous amount of insight into loop errors in this manner. :) ). Generally you want to avoid one major error that novice and experienced programmers all make

If it compiles and runs, it must be correct!

College of Computer Studies

128

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

This is a bad attitude and approach to programming. Once your program compiles and runs, you must enter a phase of intensive evaluationone that is rigorous enough to make you feel confident about your code. So how do we test this little applet? We do have to change its size numerous times, and we should probably try the following:

Several narrow sizes Several wide sizes Several medium sizes We should also try to size the applet so the rightmost circle just touches the right edge. Then we should widen the applet just a bit more to see if we can cause a partial circle to be drawn.

Once we have done this we can be reasonably sure our loop is correct. Note that the statement is "reasonably sure." Why does the above say to look at the left and right circles? These are the ones that are closest to the edge of the applet. These are the "boundary circles." Things that are done in the first and last iterations of a loop represent the boundary conditions. If we do not initialize things correctly, the first (or more) iterations may be incorrect. If we do not construct the loop guard correctly, the last iteration or iterations may be wrong. A good programmer tests the program's loops in a manner that determines if the boundary conditions are dealt with correctly. If we check the first (or left-side) circle and see that it is next to the left

College of Computer Studies

129

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

edge of the applet, then it might be safe to conclude that we are starting the loop correctly. If we check the tenth (or right-side) circle and see that it is reasonably close to but not beyond the right edge of the applet, then it may be safe to conclude that we are probably terminating the loop correctly. Testing the boundary conditions is very important. Here is a loop that is supposed to print the values 1 through 5. Is it correct? int i, yLoc;

for (i = 0, yLoc = 25; i < 5; i = i+1, yLoc = yLoc + 15)

g.drawString ("value of i is " + i, 25, yLoc);

} What will the output of this loop be? Check it carefully before reading the next part? Write the output on a piece of paper! The output will be: 0

College of Computer Studies

130

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

4 and not the desired 1 through 5. This code exhibits the "off by one bug" that is famous in loop building. The initial value is off by one (we display 0 instead of 1), and the last value is off by one (we display 4 instead of 5)why?

The first reason is the initialization of iit should have been set to 1 The second reason is the testthe test only checks for less thanand when i is equal to 5, it is not less than 5, so the fifth iteration never occurs. This problem is fixed by changing the "<" operator to "<=".

Debugging loops can be challenging. If you cannot debug a loop, you may have to rethink it entirely. Sometimes you have to throw a loop away and start with a fresh approach. One thing is certain, avoiding errors in loops is not possible, but practice with loops will make fixing loop errors less bothersome. 3.3.1 The Process of Programming In the first unit of this course a four-step process for developing Web pages was described to you. Those steps were

College of Computer Studies

131

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

1. defining the Web page content 2. planning the look of the page and the needed links 3. implementing the Web page by writing it incrementally in small steps 4. evaluating the Web page in two ways: testing to see if the HTML is correct and looking to see if you like it This process is, in essence, the same process that programmers use to write a program. In this module, we will get into writing complex programs from scratch. When building complex programs, you need to pay attention to the process of programming. We will slightly modify the Web creation process and call each component a phase instead of a step. The revised process as applied to programming now looks like this

define and/or redefine the problem plan a solution to the problem code the solution evaluate and test everything

The overall model is actually circular instead of linear; that is why the numbers disappeared. Here is a picture of the model:

College of Computer Studies

132

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

As the programming problem is solved, this process is applied by the programmer. Take a guess where most of the time is spent. Do not look ahead at the next line! The answer is in evaluation and testing, but we're getting ahead of ourselves. You have to start by defining the problem in your own words: you have to make it your own and for most of us that means restating it in our own words. You often redefine the problem as part of doing so. You may have to ask questions to further your understanding of the problem. Once you have defined the problem, you have to evaluate your restatement to be sure that you are solving the correct problem. Don't laughsolving the wrong problem is a common occurrence in a programming class. If your evaluation shows that your restatement or redefinition is correct, you must begin to plan your solution (your program). This is where problem-solving skills come into the programming process. Most programmers solve a very small part of the original problem first, and then they solve the next small piece. This process is called divide and conquer. If you divide the problem into little pieces, a

College of Computer Studies

133

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

big problem can often be reduced to a series of smaller and simpler problems, each of which may be easier to code in Java. Once you have decided which piece of the problem to solve, you evaluate your decisionback to evaluation and testing again! Then you plan out your Java code for the simpler problem and evaluate the plan. Now comes the actual coding, which must be tested and evaluated for errors. Once this test demonstrates that the code works as it is supposed to, you must return to the original problem with your working code for the piece that you've solved, and begin the process again. This may sound tedious and wasteful, but if applied in a reasonable manner it will save you a great deal of time. Many novice programmers (and experienced ones, too) take a problem, go to the computer, and begin to code the solution immediately. While they may think that this is the fastest way to get the job done, our experience over the years is that the more time you spend on paper with this process, the less time you spend at the keyboard. Programming is not coding. Coding is not programming. The entire process as outlined above is programming. If you follow the process, you will actually find yourself spending as few hours coding at the keyboard as possible. 3.3.2 Designing a Simple Class

Averaging Applet Answering the Questions 134

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Making the Averaging Calculation a Separate Class The CustomAverage Class

This is a very long module. There is very little new syntax in this module. We use some of the ideas presented in earlier readings for the first time, such as a custom Font object.

In this module, we first build an Applet that calculates the average of two numbers. Then we move the code that performs the averaging function into a separate class: the CustomAverage Class.

In the next module, we discuss how to build helper classes to simplify our code. Simpler code is easier to read, maintain and modify in the future.

Finally, we design and build a slightly more complex program. It is more extensive than the averaging program we first built, so we plan an overall solution to the problem and design the classes we need before we begin coding.

Averaging Applet The Averaging Applet's purpose is to calculate the average of two numbers. The problem definition is:

get two numbers from the user. compute the average of the two numbers. display the average.

College of Computer Studies

135

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

This is a very straightforward and simple problem definition, so there is probably no need to redefine it. Next, we must plan a solution. Using OOP (Object Oriented Programming) ideas, we should first identify the data that we need to solve the problem. The data needed are:

the first number. the second number. the average.

Now we have to list what the program must do with the data. This list of things we must do with the data will become the list of methods we need to solve the problem.

get the first number from the user get the second number from the user compute the average of the first and second number display the average

This group of data and methods form the skeleton of a class. Notice that we have not discussed how to store the numbers, how to compute the average, how to get the numbers from the user, or how to display the average once we compute it. They are important, but they are details of implementation, not planning. That is the next stage. What we must do now is to carefully compare our class skeleton to the problem statement (evaluation again), to see if we are solving the correct problem. It
College of Computer Studies

136

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

seems we are. Now we can begin to discuss how to store the numbers and make more decisions. For example:

Are the numbers the user enters decimal (real) numbers or whole (integer) numbers?

Is the average a real number or an integer?

Once we satisfy these questions we can move the process into the methods. Some of what we must discuss must include the following:

How do we get the numbers from the user? Do they type them in, or do we provide a calculator style keypad?

How do we compute the average? How do we display the average?

Answering the Questions

Are the numbers the user enters reals or integers? We dont know how to get real numbers from the user (there is a way and it is not difficult but we will stay with integers).

Is the average a real number or an integer? We can compute a value to a real using a new piece of syntax called casting. We will make the average a real number.

How do we get the numbers from the user? Do they type them in or do we provide a calculator style keypad? We could build a graphics keypad using 137

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

a layout manager and buttons; that would be fairly straightforward and interesting. The problem arises in getting the input. Each button will give us a simple integer value between 0 and 9. We would have to keep track of the individual entries and figure out just how the button sequence 1 -> 3 -> 5 could be converted to the integer value 135. This is doable with the skills you will have at the end of this module and we encourage you to consider doing this as an interesting excursion. For purposes of this discussion, however, we will provide two TextField objects, one for each value the user enters.

How do we compute the average? We will add the two numbers together and divide by 2. Unfortunately that computation will always give us an integer result, even if we assign the value to a float or double variable. We have to do what is called a cast. We have to force Java to treat one of the users numbers as a real number. Remember that if two int values are added, subtracted, multiplied, or divided, the result is always an integer. In the case of division, the decimal part is truncated, not rounded. Thus the expression 3/2 evaluates to 1. If the result is assigned to a real variable, the result will be 1.0 and not 1.5. Assuming that i1 and i2 are int variables and that avg is a double variable, we can get an accurate real value with this syntax: avg = ((double) i1+ i2) / 2; This new syntax (double) is called a cast, and it tells Java that for the purpose of the addition (i1 + i2), treat i1 as a double, making the result of the addition a double. When this resultant double is divided by 2, it evaluates to a double that is assigned to

College of Computer Studies

138

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

the variable avg. Read that one or two more times! It was difficult to type, so it has to be difficult to read.

How do we display the average? We can use a third TextField to print the average. If we want to use a drawString method and a layout manager to control the look of the program, we have a problem. We have to add a Canvas object to a panel in one of the layout areas, but that is more work than we want to do at this point (if you want to try it anyway, the text shows how to write a Canvas class and how to use it). One more thingif you look at the discussion of TextField on page 743 of the book Schildt, you will see a method called setEditable(boolean canEdit). If we have a TextField called display, we can type the following line of code: display.setEditable(false); and the user cannot enter text into display. We should do this for the TextField that we will use to show the average.

Here is a simple applet that solves this problem. There is no layout manager here so the default FlowLayout is used and the resultant applet, while doing the job, does not look very appealing.

/**************************************************************

Averaging Applet

College of Computer Studies

139

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

/**************************************************************/

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class Average extends Applet implements ActionListener

public TextField input1, input2, display;

public Label labelTitle, label1input, label2input, label3display;

public Button b1;

public int num1, num2;

College of Computer Studies

140

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

public double avg;

public void init( )

input1 = new TextField(12);

input2 = new TextField(12);

display = new TextField(12);

input1.setText("0");

input2.setText("0");

display.setText("");

College of Computer Studies

141

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

display.setEditable(false);

labelTitle = new Label("Average Calculator"); label1input = new Label("First Number"); label2input = new Label("Second Number"); label3display = new Label("Computed Average"); b1 = new Button("Push to Compute Average"); b1.addActionListener(this); add(labelTitle); add(label1input); add(input1); add(label2input); add(input2); add(b1); add(label3display); add(display);

} public void actionPerformed(ActionEvent e) { num1 = Integer.parseInt(input1.getText()); num2 = Integer.parseInt(input2.getText());

College of Computer Studies

142

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

avg = ((double)num1 + num2) / 2 ; display.setText(""+avg); } } If we were to take the time to develop this as a group project, we would add one set of components at a time. We would start with the labels, add the code for them, compile, debug if needed, and look at the output. We would then add the TextFields in the same manner. Then the Button. Next we would add the functionality found in the actionPerformed() method and test that. If we did not like what we saw, we would redefine our problem, change our plan, and recode the parts we did not like. Then we would test again. Once we have good output, we would discuss adding the needed layout manager(s), and font and color changes. We would make these additions in reasonable segments: possibly the layout manager first, then the font changes, and then the colors. Each of these steps would be added, tested, and evaluated for correctness of behavior and appearance and for ease of use. Thus the process we described earlier also works for these later (and larger) problems. You need to work in a manner that solves smaller segments of the problem, one at a time, in a logical manner. We suggest that you copy this into your demo applet file and work with it. Again, tinkering is a reasonable thing to do. You might want to add a layout manager, to see if you can get a more appropriate arrangement of the components.

College of Computer Studies

143

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Making the Averaging Calculation a Separate Class The "Average" class we wrote above did two different tasks: 1. draw Labels, TextFields, Buttons, etc on the screen. 2. calculate the average. It would be nice to separate the two tasks into two separate classes, because in a large project in which a number of people are collaborating:

The averaging functionality may be needed for a number of other tasks by other people. Some of them may not want to draw anything. A class that just performs the "averaging" task would be useful to them.

We may want to use the drawing code to perform other actions later on, such as addition, subtraction, etc. By separating out the drawing part, it will be easier to extend the drawing functionality.

As you can infer from the above, it is a good design idea in general to build components that have well-defined roles to play. Especially in a large system, it is easier to assemble smaller components, which may be written by different people, to build bigger and bigger components. Before we start this, we must make one disclaimer. The applets that we are using are literally "toy" applets in terms of size, complexity, error checking, and functionality. We would never go out and buy an averaging applet like this one. They are strictly demonstrations of concepts. If we were to write a real applet it

College of Computer Studies

144

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

would probably take us at least one entire semester, probably longer. So for the following discussion we are going to do a lot of work for very little return. The clich that the process is the important focus is very true for this discussion. The class that we will create is very small, but it is useful to show you as a first example how a programmer can define his or her own class. When we define a class, it should deal with a well-defined set of content. The Color class deals only with colors in the applet. It does not worry about fonts or circles. The Font class deals only with fonts; we will use this class in a later part of this module. The Graphics class is bigger than the Color or Font class, but it deals only with graphics in the applet. It can use color objects and font objects, but it does not change the color or font: it just draws. Our problem is to take the averaging material out of the applet and put it into its own separate class that we will call the CustomAverage class. The applet will instantiate a CustomAverage object and use this object for computing averages. With that brief introduction in mind, lets pose some questions and answer them, which, you will recall, is part of the process we use to develop programs.

What will our CustomAverage class do? It will compute the average of two integers.

Where will the two integers come from? Good question. Who deals with the user via a GUI? The applet does, so the applet will provide the two integers to the CustomAverage object.

College of Computer Studies

145

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

How will the average class display the average? Another good question, and we answer it the same way: who deals with the user via a GUI? The applet does, so the CustomAverage class must return the computed average to the applet.

Classes need a constructor. What will the constructor for the CustomAverage class do? In reality it will do very little. We will use it to initialize its variables.

Will the class CustomAverage have any interface with the user of the applet? No. The user will not even know that the class exists. The behavior will be just like the original applet above. The only communication for the CustomAverage class will be with the applet.

Below is the code for the CustomAverage class. Following that is the new applet that uses the CustomAverage class. These code samples are followed by a discussion that will touch on certain portions of the code. The CustomAverage Class

/************************************************************** / / / CustomAverage class 12.14.98 jar

/*************************************************************/ import java.awt.*; 146

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

import java.applet.*; import java.awt.event.*; public class CustomAverage { /* average is an instance variable -- it is called an "instance" variable since each instance or object of this class will have its own copy of this variable */

public double average;

// The constructor is given below it is just initializing // the variable average to zero public CustomAverage( ) { average = 0.0; }

// The following getAverage method is the only // other method in the class // it must have two integer values provided by // the client class so it can sum them and compute // the average. The (double) in front of the // variable num1 is called a cast it forces Java

College of Computer Studies

147

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// to treat num1 as a double so the result of the // entire expression will be a double. // the type of the method is double not void this // means that the method must return a double // to the client class. public double getAverage(int num1, int num2) { average = ( (double)num1 + num2) / 2; return average; } } The AverageApplet class follows. We changed its name from Average to AverageApplet to try to avoid some confusion. The one thing to look at is the call of getAverage() in the actionPerformed method. Notice that we used method calls from the Integer class to get the integer values from the two TextFields. This may look weird, but it is very reasonable code. In order to use the getAverage() method, we must provide two integer values as data to that method. These integer values are the values to be averaged. Those values must be what the user enters into the TextFields. As you notice below, the appearance of this applet is the same as the previous applet. Our implementation just got more elegant. /**************************************************************

College of Computer Studies

148

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

AverageApplet uses CustomAverage class

/*************************************************************/ import java.awt.*; import java.applet.*; import java.awt.event.*;

public class AverageApplet extends Applet implements ActionListener { public CustomAverage average; // instantiate a CustomAverage object "average" public TextField input1, input2, display; public Label labelTitle, label1input, label2input, label3display; public Button b1; public int num1, num2; public void init( ) { average =new CustomAverage( ); // new the average object input1 = new TextField(12); input2 = new TextField(12); display = new TextField(12);

input1.setText("0"); input2.setText("0");

College of Computer Studies

149

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

display.setText(""); display.setEditable(false);

labelTitle = new Label("Average Calculator"); label1input = new Label("First Number"); label2input = new Label("Second Number"); label3display = new Label("Computed Average");

b1 = new Button("Push to Compute Average"); b1.addActionListener(this);

add(labelTitle); add(label1input); add(input1); add(label2input); add(input2); add(b1); add(label3display); add(display); }

public void actionPerformed(ActionEvent e) {

College of Computer Studies

150

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// the next line uses the getAverage method // in the CustomAverage class to // compute the average. The two parameters of the // method calls are actually // method calls to the Integer class that // will return the integer values the // user entered into the two TextFields display.setText (""+average.getAverage(Integer.parseInt(input1.getText()), Integer.parseInt(input2.getText()) )); } } The last line of code above may be bothering you. Let's look at it more closely. We must provide two integer values to the CustomAverage object for averaging. Those two values must come from the user. In the example above, we put the code that actually extracts the integer value from the TextField in the parameter list. This code will return an integer for each call and that integer is passed to the CustomAverage object's getAverage method. The getAverage method returns a double that is the average of the two numbers. We could have written that code as below, using three local variables we have named num1, num2, and avg. The variables num1 and num2 get their values from the parseInt method of the Integer class. The parameter is the text that the user entered into the TextFields. Then we call getAverage and it returns the average of num1 and num2, which in

College of Computer Studies

151

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

turn is stored in the variable avg. We use avg to display the text in the display TextField. public void actionPerformed(ActionEvent e) { int num1, num2; double avg; num1 = Integer.parseInt(input1.getText()); num2 = Integer.parseInt(input2.getText()); avg = average.getAverage(num1, num2); display.setText(""+ avg); } We have now seen the development of two classes. The first one (Average) was an applet that finished up an idea we discussed earlier. The second one (CustomAverage) moved the averaging material out of the applet into a class of its own. In order to run this, you will need two .java files. One called CustomAverage.java and one called AverageApplet.java. When you compile the AverageApplet.java file, the Java compiler will also compile the CustomAverage.java file and write two .class files: AverageApplet.class and CustomAverage.class. The .html file needs only refer to the AverageApplet.java class.

College of Computer Studies

152

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Copy these programs into your own files and run them. We also encourage you to tinker with them, as we have done in previous modules. The Need for Helper Classes In the last section we moved the averaging code out of the applet and into a new class that we called CustomAverage. The general goal is to build classes that deal with specific parts of the problem. The CustomAverage class was a very small class and serves only as a demonstration of how to build a programmerdefined class. This discussion is somewhat different. We will build a programmer-defined class but for slightly different reasons. Our applet is a very simple applet. It has a Button, some TextFields and some Labels. Yet it is getting crowded and messy. There is a lot of code required to build each Button, TextField, and Label. What if we had 15 Buttons, 5 TextFields, and some Labels (not to mention several layout managers) to control the look of the interface? The applet would grow very large and difficult to edit. One goal we can try to achieve in an object-oriented language like Java is to keep things small, and easy to read and modify. We should look at the Applet class as the leader of the solution to the problem we are solving. It is like the president of a company. The company president does not unload the trucks at the loading docks and does not stuff products that have been sold into boxes for shipping. The warehouse team unloads the trucks and the shipping department

College of Computer Studies

153

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

sends out merchandise. There is a division of labor in companies. We should have a similar division in our solutions to problems. Example: Average Applet with a Helper Class The CustomAverage class was a first step toward building that division of labor. A second step is to move much of the Button material out to a Button division or to a new class that we will call CustomButton. The idea here is to shift the code for building buttons into a new class. The applet will still have to instantiate the buttons, but it will do that by passing messages to the new class. As we have done in the past, let's look at the code first and then dissect it carefully. We are going to add some different fonts and colors, so you may want to look over that material again. It can be found in Schildt on pages 712-23. The AverageApplet Class /**************************************************************

* Averaging Applet uses CustomButton class

* SSD1->Java Language->Designing Classes->

->Helper Class->Designing a Helper Class

**************************************************************/

College of Computer Studies

154

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

import java.awt.*; import java.applet.*; import java.awt.event.*;

public class AverageApplet extends Applet implements ActionListener { public CustomAverage average; // instantiate an CustomAverage object called average public TextField input1, input2, display; public Label labelTitle, label1Input, label2Input, label3Display;

// new for this discussion public Color newColor; public Font newFont; public CustomButton b1;

public int num1, num2;

public void init( ) {

College of Computer Studies

155

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// new for this discussion newColor = new Color(125, 0, 255); newFont = new Font("Helvetica", Font.BOLD + Font.ITALIC, 18); b1 = new CustomButton("Push for Average", newColor, Color.yellow, NewFont);

// much of this is unchanged from the previous discussion average =new CustomAverage( ); input1 = new TextField(12); input2 = new TextField(12); display = new TextField(12); input1.setText("0"); input2.setText("0"); display.setText(""); display.setEditable(false); labelTitle = new Label("Average Calculator"); label1Input = new Label("First Number"); label2Input = new Label("Second Number"); label3Display = new Label("Computed Average"); b1.addActionListener(this);

add(labelTitle); add(label1Input); add(input1); add(label2Input);

College of Computer Studies

156

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

add(input2); add(b1); add(label3Display); add(display); }

public void actionPerformed(ActionEvent e) { display.setText (""+ average.getAverage(Integer.parseInt(input1.getText()), Integer.parseInt(input2.getText()) )); } }

We moved most of the button material into the next class. We still have to instantiate and new the CustomButton object and we still have to add the ActionListener as well as the CustomButton object to the applet. However, all of the stuff that sets a button's color and font is done in the CustomButton class. Let's look at the CustomButton class next and then discuss the code in both classes. The CustomButton Class

/************************************************************** / / CustomButton Class 12.15.98

College of Computer Studies

157

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

jar

/*************************************************************/ import java.awt.*; import java.applet.*; import java.awt.event.*; public class CustomButton extends Button implements ActionListener { private Color myBackgroundColor, myForegroundColor; private String myLabel; private Font myFont; public CustomButton(String str, Color fgColor, Color bgColor, Font ft) { // first we must call the constructor in the parent and send up // the label for the button super(str); // next we store the values provided by the applet in case we need // them in the future myLabel = str;

myBackgroundColor = bgColor; myForegroundColor = fgColor; myFont = ft; // we then set the button to the requested values provided

College of Computer Studies

158

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// by the applet setBackground(myBackgroundColor); setForeground(myForegroundColor); setFont(ft); } public void actionPerformed(ActionEvent e) { // this is empty -- in order to use the listeners we must // provide this method even if it is empty. } } Dissecting the CustomButton Class his CustomButton class is a helper class. It takes some work off the "shoulders" of the applet. It builds the button for the applet. Let's look at the first line or header of the class: public class CustomButton extends Button implements

ActionListener This tells us a lot. First it is public, so the applet can use an object of this class. Next we see that this is a subclass of Button, which means that it inherits everything a Button object can do. Next we see that this is also using parts of the

College of Computer Studies

159

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

ActionListener class. We have seen all of this before in the declaration of an Applet class. Now let's look at the code, starting with the instance variables for the class. We have already discussed variables in an earlier module. Let's look at instance variables in more detail. Here are the instance variables copied from the CustomButton class above: private Color myBackgroundColor, myForegroundColor;

String myLabel;

Font myFont; Each CustomButton object will have its own set of these four variables. This means that each CustomButton can have its own background color and font color as well as its own label and its own font. Each button is an instance of a class so these are instance variables. Other than this descriptor, they are like ordinary variables. We use these four variables to store the information that is provided by the applet class in the parameter list. We copy those provided values into these variables in the constructor method, which is shown below without the comments: public CustomButton(String str, Color fgColor, Color bgColor, Font ft)

College of Computer Studies

160

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

super (str);

myLabel = str;

myBackgroundColor = bgColor;

myForegroundColor = fgColor;

myFont = ft;

setBackground(myBackgroundColor);

setForeground(myForegroundColor);

setFont(myFont);

} Let's review the rules for a constructor:

It must have no return type between the word public and the name of the method

College of Computer Studies

161

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

It must have the exact same name as the class The parameter list must contain any information that is required from the client (or in this case applet) class

We see the keyword public and then the name of the constructor, CustomButton, which is exactly the same as the class name. Then we see the parameter list. Note that the contents of this list are up to the programmer. We decided that we want the client class to provide the following four things so we can provide a customized button to the client:

The String str tells this class the requested name or label for the button. The Color fgColor tells this class the color to use for the label of the button.

The Color bgColor tells this class the color to use for the background of the button.

The Font ft tells this class the font to be used for the button's label.

We could have added or taken away items, but this list was sufficient to meet the needs of the current problem. These four values (provided via the parameter list) are available only temporarily. When the constructor method is finished execution, these four values go away forever. So we save them by copying them into the four instance variables. Note that we do not use them in this demonstration. There are times we need these values, so we save them here just to show you how.

College of Computer Studies

162

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

The first line of the constructor method is somewhat unusual: super(str); This is a call to the parent class's constructor. In this case, the parent class of CustomButton class is Button class. Hence, super(str) calls the constructor for the Button class. When we used the Button class previously, we had a line that looked like this: b1 = new Button("Push to Compute Average"); This is a call to the constructor of the Button class and we provide the label for the button. Since CustomButton is a subclass of Button, we are obligated to call the Button class constructor and provide the label for the button. In Java we do this with the following syntax. The parameter (str) contains the button's label, as provided by the applet. This must be the first line of code within the body of the constructor, or the class will not compile. Next we save the incoming values provided by the applet in the instance variables, as shown below: myLabel = str;

myBackgroundColor = bgColor;

myForegroundColor = fgColor;

College of Computer Studies

163

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

myFont = ft; Finally, we set the CustomButton attributes to the incoming values, so the button will have the correct colors and font: setBackground(myBackgroundColor);

setForeground(myForegroundColor)

setFont(myFont); The last thing in the class is an empty method called actionPerformed. This method is required because we are using the ActionListener class, and need listeners for the button. If we do not use the line of code that says the class implements ActionListener, the applet will never be notified that a click occurs on the button. However, in this demo we have nothing to do in the class when the button is clicked. In a later module we will use the actionPerformed method in this class to change the color of the button when the user clicks it. Dissecting the AverageApplet Class Let's look at how we used the CustomButton class in the applet. There are four lines of code that we need to look at:

College of Computer Studies

164

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

First the declaration: it looks like any object declaration we have seen to date. We use the class name and the identifier we choose: CustomButton b1;

Next we have to new the object: b1 = new CustomButton("Push for Average", newColor, Color.yellow, newFont); The information in the parentheses composes the parameter list. If you refer back to the discussion about the constructor, you will see that we must provide a string for the button's label, two colors and a font. If you look back at the init method, you will see the code that built one of the colors called newColor and the font called newFont. If we do not provide these four pieces of information, our applet class will not compile.

We must add the action listener. This looks like it did before: b1.addActionListener(this); so there is no change here.

We must add the button to the applet too: add(b1); so this does not change either.

Even with all this, the applet is still messy, so we could decide to build classes for CustomLabels and CustomTextFields. If we do that, our Applet would look much less messy, but more importantly it would be easier to fix when we have a bug and easier to modify when a modification is required. Why Not Do the Rest of the Widgets? Hey, why not? This will really clean up the applet. Here are the applet class and two helper classes. The CustomButton class has not changed, but there are two 165

College of Computer Studies

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

new helper classes: one for the Labels and one for the TextFields. There is no discussion here; if you follow what was done with the CustomButton class you should be able to follow the two new classes. The only thing they are missing is the listener code, since we are not using listeners for TextFields.

First the Applet Class /************************************************************

* Averaging Applet uses CustomButton class

* SSD1 -> Java Language -> Designing classes -> Designing a helper class

* -> Why not do the rest of the widgets (3.1.2)

*************************************************************/

import java.awt.*;

import java.applet.*;

College of Computer Studies

166

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

import java.awt.event.*;

public class AverageApplet extends Applet implements ActionListener

public CustomAverage average; // make a CustomAverage object called average

public CustomButton b1;

public CustomTextField input1, input2, display;

public CustomLabel LabelTitle, Label1input, Label2input, Label3display;

public Color newColor;

public Font newFont;

College of Computer Studies

167

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

public int num1, num2;

public void init( )

newColor = new Color(125, 0, 255);

newFont = new Font("Helvetica", Font.BOLD + Font.ITALIC, 24);

average =new CustomAverage( );

b1 = new CustomButton("Push for Average", newColor,

Color.yellow, newFont);

input1 = new CustomTextField(12,"0", newColor, Color.yellow,

newFont, true);

College of Computer Studies

168

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

input2 = new CustomTextField(12, "0", newColor,

Color.lightGray, newFont, true);

display = new CustomTextField(12, "", newColor, Color.red,

newFont, false);

LabelTitle = new CustomLabel("Average Calculator", newColor,

Color.pink, newFont );

Label1input = new CustomLabel("First Number", newColor,

Color.white, newFont);

Label2input = new CustomLabel("Second Number", newColor,

Color.orange, newFont);

Label3display = new CustomLabel("Computed Average", newColor,

College of Computer Studies

169

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Color.gray, newFont);

b1.addActionListener(this);

add(LabelTitle);

add(Label1input);

add(input1);

add(Label2input);

add(input2);

add(b1);

add(Label3display);

add(display);

College of Computer Studies

170

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

public void actionPerformed(ActionEvent e)

display.setText(""+

average.getAverage(Integer.parseInt(input1.getText() ),

Integer.parseInt(input2.getText() ) ));

Now the Two New Helper Classes /**************************************************************

/ CustomLabel Class

College of Computer Studies

171

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

/ 12.15.98

/ jar

/*************************************************************/

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class CustomLabel extends Label

private Color myBackgroundColor, myForegroundColor;

private String myLabel;

College of Computer Studies

172

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

private Font myFont;

public CustomLabel(String str, Color fgColor, Color bgColor, Font ft)

super(str);

myLabel = str;

myBackgroundColor = bgColor;

myForegroundColor = fgColor;

myFont = ft;

setBackground(myBackgroundColor);

setForeground(myForegroundColor);

setFont(ft);

College of Computer Studies

173

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

/**************************************************************

/ CustomTextField Class

/ 12.15.98

/ jar

/*************************************************************/

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

College of Computer Studies

174

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

public class CustomTextField extends TextField

private Color myBackgroundColor, myForegroundColor;

private String myLabel;

private Font myFont;

private int mySize;

private boolean myCanEdit;

public CustomTextField(int size, String str, Color fgColor,

Color bgColor, Font ft, boolean canEdit)

College of Computer Studies

175

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

super(size);

myLabel = str;

myBackgroundColor = bgColor;

myForegroundColor = fgColor;

myFont = ft;

mySize = size;

myCanEdit = canEdit;

setBackground(myBackgroundColor);

setForeground(myForegroundColor);

setFont(ft);

setText(str);

setEditable(myCanEdit);

College of Computer Studies

176

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Again we encourage you to copy these into files, compile them, and run them to see how they behave. Tinkering is always encouraged, especially in an area where you have never tinkered before. In summary, notice how we started building on existing code, and extending the functionality of different components. As a case in point, when it came to a point where we did a lot of things to a Button class in the general applet code, we moved the button-related functionality into a separate CustomButton class. Notice we did not create a totally new class from scratch; instead we used an existing Button class and inherited all of its properties by making it CustomButton's superclass. Thus when we want to extend the functionality and we have a pool of code, we can slice and dice existing code and add to the pieces. This ease of extensibility by inheriting from a superclass is one of the cornerstones of object-oriented programming. And we were able to use the CustomButton class without affecting any other code that continues to use the Button class. Note that even if we had the source code for the Button class, it would not have been easy to make additions to the Button class itself. This is

College of Computer Studies

177

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

because we have to worry about who else is using the Button class, and whether we will be breaking their code if we make changes to it. 3.3.4 Building a Complex Program

Defining the Problem Planning a Solution VendingMachine Class Cup Class Coding the VendingMachine Class Coding the Cup Class Testing and Evaluation

Till now, we have looked at writing simple programs in order to illustrate the use of different programming constructs. It is time to make use of all of the information to build slightly more complex programs. In this section, we will build a vending machine program. Let us follow the process of programming that we discussed earlier in this unit. Defining the Problem We want a vending machine to sell the following drinks: Coffee, Orange Juice, Water, and Milk. The drinks can be sold in two different sizes: small and large. The large size will be twice as large as the small size, and hence will cost twice as much. The cost of different drinks will be different. Small coffee will cost $1.00. Small Orange Juice will cost $1.5. Small Water will cost $0.5. Small milk will cost
College of Computer Studies

178

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

$1.00. The vending machine will go through the following state transitions depending on the actions of the user: 1. In the initial state the system should prompt the user, select the drink (Orange Juice, Coffee, Water, or Milk). 2. Once the user selects the drink, the system should prompt the user to select the size of the drink (small or large). 3. Next, the system should specify the cost of the drink and ask the user to deposit money. 4. Once the money is deposited the system should fill the cup with the drink and ask the user to take it. 5. Once the user has taken the drink, the system returns back to the original state, prompting the user to select a drink. Planning a Solution To solve this problem, we need to have a class that extends Applet. Let's call this class VendingMachine. This class will be in charge of drawing all the widgets on the screen, and moving the vending machine through various phases as described above. We also need another class that denotes the cup. Let's call this class Cup. This class will recognize different kinds of drinks, their sizes, and their prices. It will also be responsible for drawing the cup, filling the cup with different drinks, emptying the cup, and so on. VendingMachine Class

College of Computer Studies

179

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

This class should have


four different buttons for the user to select the four different drinks. two different buttons for the user to select the two different drink-sizes. a TextField for the user to deposit money. a TextArea for the system to display user prompts. space to display the cup. (Note that the cup will display itself.)

To display all these widgets in a proper layout, we will need panels and we will use different layout managers.

Let us draw the buttons for the drinks on the top left corner, one below the other.

Below the drinks, we will put the buttons to choose the size of the drink (again one below the other).

On the right side of the display, we will put the TextArea to display user prompts.

Below the TextArea, we will display the cup, and below that we will display the TextField for the user to deposit money.

Below the TextField, we will have two buttons: one for the user to press after he or she puts in the money, and another to take the drink.

Our final look should look like the following:

College of Computer Studies

180

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Cup Class The Cup class will determine the price of the drink and fill the cup with drink. It needs to paint itself and resize itself when requested by the browser. There are two ways to determine the size of the area that is available to draw the Cup: 1. Make hard assumptions on the size, and force the applet to be of at least a certain size in order for the cup to be the required size. In this approach, we will have to put the exact dimensions in the code. The X and Y coordinates will have to be relative to the (0, 0) of the applet. It can get pretty difficult to calculate all the numbers in our head. 2. Or, we can inherit Cup from a Component. In this case, we can dynamically determine the size of the cup by using the getSize method. Also, the X and Y coordinates will not be relative to the applet, but relative to the top-left corner of this Cup object. This makes our calculations a lot easier. So, let us inherit Cup from Component. Coding the VendingMachine Class Now let us implement our solution. Let us first start with the VendingMachine class. As described above, we need to create different widgets. The code below has a number of comments. Follow the comments as you read through the code. In the following code, we use a class named Dash, which we will discuss later. import java.awt.*; import java.applet.*;

College of Computer Studies

181

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

import java.awt.event.*;

public class VendingMachine extends Applet implements ActionListener { public Button coffee, orange, water, milk; // For choosing drinks public Button small, large; // For choosing size of the drink. public Button deposit, take; // For depositing money and taking drink.

public TextArea display; // To display prompts to the user public TextField depositField; // For User to deposit money

public String titleMsg, guideMsg; // To display various prompts

public Cup cup; public String drink, drinkSize; // The drink and its size.

public double price; // Price of the drink

public void init() { Panel buttonPanel, rightPanel; // Panel on the left and right Panel depositPanel; // Panel to hold the "deposit" and "take" buttons Dash dash; // To display a line separating the

College of Computer Studies

182

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// drink buttons and size buttons

cup = new Cup();

// Create all the buttons coffee = new Button(cup.COFFEE); orange = new Button(cup.JUICE); water = new Button(cup.WATER); milk = new Button(cup.MILK); small = new Button("Small"); large = new Button("Large"); deposit = new Button("Deposit"); take = new Button("Take the glass");

// Create the TextArea and TextField display = new TextArea(); depositField = new TextField();

dash = new Dash();

// Create the Panels buttonPanel = new Panel(new GridLayout(7, 1, 10, 10)); rightPanel = new Panel(new GridLayout(3, 1, 10, 10)); depositPanel = new Panel(new GridLayout(3, 1, 10, 10));

// Layout for the Applet. setLayout(new GridLayout(1, 2, 10, 10));

College of Computer Studies

183

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// Add the buttons to the buttonPanel, and add buttonPanel to Applet. buttonPanel.add(coffee); buttonPanel.add(orange); buttonPanel.add(water); buttonPanel.add(milk); buttonPanel.add(dash); buttonPanel.add(small); buttonPanel.add(large); add(buttonPanel);

// Add the appropriate components to the depositPanel depositPanel.add(depositField); depositPanel.add(deposit); depositPanel.add(take);

// Add the display, cup and depositPanel to the rightPanel rightPanel.add(display); rightPanel.add(cup); rightPanel.add(depositPanel); add(rightPanel);

// User cannot edit the TextField. // It is for prompts generated by the system. display.setEditable(false);

// Add actionListeners for the buttons. coffee.addActionListener(this); orange.addActionListener(this);

College of Computer Studies

184

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

water.addActionListener(this); milk.addActionListener(this); small.addActionListener(this); large.addActionListener(this); deposit.addActionListener(this); take.addActionListener(this);

// Display the title. titleMsg = new String("CTE SSD1 - SUPER SOFT DRINK ONE");

// Set the initial state: the user should be able to select the drink. selectDrink(); } Next let us write the methods that will take us from one state to the next. In each state, we need to do the following things: 1. Check for validity of input, if there is a possibility that the user can give an invalid input. In our case, the only time the user can input something invalid is when he or she deposits an insufficient amount of money. 2. Take appropriate action based on the user input. For example, note down the kind of drink, its size, its price, etc. 3. Display proper user prompt. 4. Disable the buttons and other widgets that need to be disabled, and enable the ones that need to be enabled. Here are the relevant methods that will transition the state:

College of Computer Studies

185

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// Ask the user to select the drink. public void selectDrink() { // The drink buttons should be enabled, and others disabled. coffee.setEnabled(true); orange.setEnabled(true); water.setEnabled(true); milk.setEnabled(true); small.setEnabled(false); large.setEnabled(false); deposit.setEnabled(false); depositField.setEnabled(false); take.setEnabled(false);

// The cup should be empty. cup.setDrinkSize(cup.EMPTY); cup.fill();

// Prompt the user to selet the drink. guideMsg = "Please choose your drink."; display.setText(titleMsg + "\n" + guideMsg); }

// Ask the user to select the drink size. public void selectDrinkSize(String dr) { drink = dr; // Get the price of the drink.

College of Computer Studies

186

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

price = cup.setDrink(drink); // Disable the drink buttons, and enable the size buttons. coffee.setEnabled(false); orange.setEnabled(false); water.setEnabled(false); milk.setEnabled(false); small.setEnabled(true); large.setEnabled(true); guideMsg = "Please choose the size of your " + drink + "."; display.setText(titleMsg + "\n" + guideMsg); } // Ask the user to deposit money public void deposit(String size) { drinkSize = size;

// If the size is Large, double the price. if (drinkSize.equals (cup.LARGE)) { price = 2 * price; }

small.setEnabled(false); large.setEnabled(false); deposit.setEnabled(true); depositField.setEnabled(true);

guideMsg = "Please deposit " + price + " dollars."; display.setText(titleMsg + "\n" + size + " " + drink + "\n" + guideMsg);

College of Computer Studies

187

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// Ask the user to take the drink public void takeDrink() { Double amount;

amount = new Double(depositField.getText());

// See if the deposited amount is at least equal to the cost of the drink. // If so, fill the cup, and ask the user to take the drink. // Or else, ask the user to deposit sufficient amount. if (amount.doubleValue() >= price) { cup.setDrinkSize(drinkSize); cup.fill(); display.setText(titleMsg+"\n"+"Please take your drink."); depositField.setEnabled(false); depositField.setText(""); deposit.setEnabled(false); take.setEnabled(true); } else display.setText(titleMsg+"\n"+"Insufficient amount.\n"+ "Please deposit "+price+" dollars."); }

College of Computer Studies

188

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

Next, we need to write the event handler to respond to button clicks. Here it is: // Respond to button clicks. public void actionPerformed(ActionEvent e) { String action = e.getActionCommand();

// If the user selcts the drink, next ask to to select the size. if (action.equals(coffee.getLabel())) selectDrinkSize(cup.COFFEE); else if (action.equals(orange.getLabel())) selectDrinkSize(cup.JUICE); else if (action.equals(water.getLabel())) selectDrinkSize(cup.WATER); else if (action.equals(milk.getLabel())) selectDrinkSize(cup.MILK);

// If the user has chosen the size, ask them to deposit money else if (action.equals(large.getLabel())) deposit(cup.LARGE); else if (action.equals(small.getLabel())) deposit(cup.SMALL);

// If the user has deposited sufficient money, ask them to take the drink else if (action.equals(deposit.getLabel())) takeDrink();

// If the user has taken the drink, go back to the initial state // and ask the user to select the drink else if (action.equals(take.getLabel())) selectDrink(); }

College of Computer Studies

189

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// We have come to end of class definition for VendingMachine. // So end it with a curly brace. } Note that the final closing curly brace is to end the class definition for VendingMachine, and is not part of the actionPerformed method. This completes our VendingMachine class. Note that we used a class named Dash. This class is used to display a horizontal line to separate the drink buttons from the size buttons. Dash needs to stretch and shrink itself if the applet is resized. To do this easily, we made Dash as a separate class and inherited it from Component. Here is the Dash class: import java.awt.*;

public class Dash extends Component { public void paint(Graphics g) { int height, width;

height = this.getSize().height; width = this.getSize().width;

College of Computer Studies

190

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

g.fillRect(0, (height - 5)/2, width, 5); } } Coding the Cup Class As we said before, we will inherit the Cup class from Component. This class has to know about the different drinks it can hold, their prices, their colors, etc. Thus, we need to have a paint method that will draw the cup. We also need a fillCup method that will animate the filling of the cup. setDrink and setDrinkSize methods are also needed; these methods will update the object to reflect the drink and size choices made by the user. The setDrink and setDrinkSize methods were called in the VendingMachine class. As a helper method, we need a drawWaves method that will draw waves on top of the drink. Here is the implementation. import java.awt.*;

public class Cup extends Component {

// The drinks public String COFFEE = "Coffee", JUICE = "Orange Juice"; public String WATER = "Water", MILK = "Milk";

College of Computer Studies

191

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// The size public String EMPTY = "Empty", SMALL = "Small", LARGE = "Large";

// The increment in which the cup should be filled to illustrate animation. public int FILLSTEPS = 100;

// The drink chosen by the user. public String drink = "None";

// The level to which the cup should be filled -- depends // on the size chosen by the user. public int level = 0;

public void paint(Graphics g) { int height, width, length, depth; int x, y;

// Get the area available to display the cup. height = this.getSize().height; width = this.getSize().width;

// Use half the height available and

College of Computer Studies

192

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// one third of the width available to draw the cup. depth = height/2; length = width/3;

x = (width - length)/2; y = (height - depth)/2;

setBackground(Color.lightGray);

// draw the empty glass with a bottom and two sides. g.setColor(Color.black); g.fillRect(x, y, 2, depth); g.fillRect(x, y + depth - 4, length, 4); g.fillRect(x + length - 2, y, 2, depth);

// pick the color of the drink if (drink.equals ("Coffee")) g.setColor(Color.darkGray); else if (drink.equals ("Orange Juice")) g.setColor(Color.orange); else if (drink.equals ("Water")) g.setColor(Color.blue); else if (drink.equals ("Milk")) g.setColor(Color.lightGray);

// fill the glass if (level > 0) fillCup(g, x + 2, y + depth - 4, depth - 4, length - 4); }

College of Computer Studies

193

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

private void fillCup(Graphics g, int x, int y, int depth, int length) { int i, j, fillLevel;

// fill the glass up to the appropriate level. for (i = 1; i < level; i = i + 1) { fillLevel = i * depth / FILLSTEPS;

// Fill the cup with 10 waves on top, // and fill the bottom with a solid rectangle. drawWaves(g, x, y - fillLevel, length, depth); g.fillRect(x, y - fillLevel, length, fillLevel);

// Pause a while to make the animation visible to the human eye. for (j = 0; j < 10000000 / FILLSTEPS; j = j + 1); }

fillLevel = level * depth / FILLSTEPS; g.fillRect(x, y - fillLevel, length, fillLevel); drawWaves(g, x, y - fillLevel, length, depth); }

College of Computer Studies

194

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// Draw the waves on top of the drink. public void drawWaves(Graphics g, int x, int y, int length, int depth) { int j;

// Draw 10 arcs for (j = 0; j < 10; j = j + 1) g.fillArc(x + j * length / 10, y - depth / 20, length / 10, depth / 10, 0, 180); }

// Remember the drink chosen by the user. Return the price of the drink. public double setDrink(String drink) { double price = 0; this.drink = drink; if (drink.equals (COFFEE)) { price = 1; } else if (drink.equals (JUICE)) { price = 1.5; } else if (drink.equals (WATER)) { price = 0.5; } else if (drink.equals (MILK)) { price = 1; } return price; }

College of Computer Studies

195

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

// Remember the size of the drink selected by the user. public void setDrinkSize(String size) {

// Based on the drink size, set the level to which the cup // should be filled. if (size.equals (SMALL)) level = FILLSTEPS/2; else if (size.equals (LARGE)) level = 4 * FILLSTEPS/5; else level = 0; }

// To fill the cup, call repaint. // The browser will then call our paint method. public void fill() { repaint(); } } Thus, we have written the code to build the vending machine. On to testing and evaluation. Testing and Evaluation

College of Computer Studies

196

COMP02 Instructional Manual


Prepared by: JAKE BENEDICT A. TIPON

AMA Computer University

1ST trimester, SY 2007-2008

When this page was written, a number of mistakes were made in the code above. They had to be corrected and checked. You will also have to go through a number of iterations of coding and testing in order to get the applet to work just the way you want it to.

College of Computer Studies

197

Das könnte Ihnen auch gefallen