73
Chapter VI Class Methods & Object Methods Chapter VI Topics 6.1 Introduction 6.2 Classes and Objects 6.3 Using Object Methods 6.4 Using the DecimalFormat Class 6.5 Displaying Graphics Characters 6.6 Drawing Polygons 6.7 Drawing Regular Polygons 6.8 Creating New Colors 6.9 Creating Random Numbers 6.10 Using Random Numbers with Graphics 6.11 Summary Chapter VI Using Methods Page 231

Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

  • Upload
    lythuy

  • View
    213

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Chapter VI

Class Methods & Object Methods

Chapter VI Topics

6.1 Introduction

6.2 Classes and Objects

6.3 Using Object Methods

6.4 Using the DecimalFormat Class

6.5 Displaying Graphics Characters

6.6 Drawing Polygons

6.7 Drawing Regular Polygons

6.8 Creating New Colors

6.9 Creating Random Numbers

6.10 Using Random Numbers with Graphics

6.11 Summary

Chapter VI Using Methods Page 231

Page 2: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

6.1 Introduction

Chapter IV started an introduction to Java Program Organization. After this, the chapter concentrated on using various methods. You did not realize it, but all the methods in the last two chapters were class methods. There are also object methods. In this chapter, you will learn the difference between classes and objects as well as class methods and object methods.

Part of the problem is that the word object has two meanings. There is the meaning of object in the general sense as the word object in object oriented programming. There is also a more technical meaning which helps to distinguish between a class and an object, and furthermore between a class method and an object method.

Right now your understanding about this object business should be that an object is some type of structure, or container that holds information like integers, characters, strings or more complex information. We can call this information data. An object stores more than data, because data by itself lacks all functionality. We want to alter data, display data, sort data, search data or perform many other data processes. All these actions on the object’s data are performed by other object members, modules that have the ability to process data. The corner stone of objects is this business of packing both the data and various modules that process the data in the same container.

Now in Chapter IV, you used a variety of methods that processed data. You saw methods capable of computing the square root, absolute value, and other mathematical computations. All these methods are called class methods. Somehow this implies that a class can also hold action modules, just like an object.

It probably all sounds very confusing. Most people are quite confused at the first introduction to all the new vocabulary words in computer science. This chapter will start by clarifying the difference between a class and an object and then continue to show you how to use object methods.

Page 232 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 3: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

6.2 Classes and Objects

The word class implies a collection of some category. In high school there may be a French class, a Geometry class, an Art class and a Computer Science class. A French class is not the same as a Geometry class, but you would expect first period Geometry to be quite similar to second period Geometry.

You can think of a class as a category, as a blue print, as a general description. You are surrounded by classes. A cat, a dog, a car, a student, a soldier, a physician, a teacher, a mother, a baby are just a few of the many classes that exist in your world. Now notice that none of these classes are specific. We all know what a cat is, but it is a general statement; unlike Fluffy, which is a specific cat you can see and pet. In this example cat is a class and Fluffy is an object.

Now you are no stranger to working with general concepts and specific cases. You have written programs that used int. The int data type is general and cannot be used by itself so you create variables like number1 and number2, each being a variable of the int type. This means that we are not interested in working with just one integer, but as many different integers as our program requires.

Does this mean that int is a class and number1 is an object? No, it does not and number1 can only store a single integer value without any modules available to process the integer value. The example on int and number1 is used to illustrate the concept of a general item like int and one specific kind of int, which is number1.

Now let us look at a class you have seen used in several program examples, the Math class. Figure 6.1 is an illustration of the Math classes with a small set of the actual members that are found in this class.

Figure 6.1Math Class

Figure 6.1 shows a Math class with ten members. The class is not complete, but that does not matter. Consider this question. How many different copies do you

Chapter VI Using Methods Page 233

abs() sqrt() min()

max() round() ceil()

floor() PI E

pow()

Expo.java

Expo.html

Expo.java

Expo.html

Page 4: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

need of the sqrt method, or the round method? Do you need to store different values of PI for different situations? Hardly, you only need one copy of each one of the class members. The values of PI and E will always be the same and the functions sqrt, abs, pow, min, max, floor, ceil and round have no reason to change.

So what is the point? The point is that we can function very nicely with one copy of a Math class. We have no need to store a variety of different types of data. When we speak about an integer, we need to know which integer we are using. Do you need to know, which square root or which PI is being used? No, they are always the same. In those cases where data does not change, where action modules always behave in the same manner, there is only one copy needed and modules or methods in such a case are called class methods. This is precisely what you did with the Math class.

Since you have only experienced class methods you may still be wondering how there can be other methods. Consider a class to handle banking operations, appropriately called the Bank class. You will see such a class actually being used later in this chapter. Let us put some data and methods in the Bank class. Data can include checkingBalance, savingsBalance, loanBalance and interestRate. Methods for a Bank class can include getChecking, getSavings, getLoan, checkingDeposit, checkingWithdrawl, savingsDeposit, savingsWithdrawl and many other banking functions.

Now a question pops up immediately. If you call method getSavings, whose savings account are you accessing for a balance? This is totally different from a squareRoot method. Square root computation is the same yesterday, today and tomorrow. A savings balance is different for different individuals.

This means it is possible to call Math.sqrt(100) and the square root of 100 will be computed. It is not possible to call Bank.checkingDeposit(1000). One thousand dollars need to be deposited in a checking account, but whose checking account? Now it makes sense to say something like tom.checkingDeposit (1000) or sue.checkingDeposit (1000). You can deposit money in Tom's account or Sue's account. So what happened to the Bank identifier? Bank becomes just like int and tom and sue are specific variables or objects of the Bank class. This also means that the methods of the Bank class are object methods.

There has been enough conversation without program examples. This section served as a brief theoretical discussion on class methods and object methods. We are now ready to look at the actual programs that use both class and object methods. Keep in mind that to use an object method, an object must first be created.

Visual Classes and Objects

Page 234 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 5: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

In AP® Computer Science – a computer course you may take next year – there was a special program called the GridWorld Case Study. Maybe you have already done a couple GridWorld Labs before you got to this chapter. Maybe you have not. In either case, it is not important to understand all the details of this program, except for the fact that multiple shapes appears on a grid. We will use this grid to help explain the difference between classes and objects in a visual manner.

In Figure 6.2 you see 4 bugs. Suppose we ask you how many classes or categories are there shown on the grid? You see 4 bugs, but they are all the same type of bug, which means there is one category or class. However, there are 4 individual bugs of the same class. We can then say that there is one class and there are 4 objects.

Figure 6.2

Chapter VI Using Methods Page 235

Page 6: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Now move on to Figure 6.3. What do you observe in the class and object department? Do you see that there are 2 classes? There are Bugs and there are Flowers. At the same time there are a total of 7 objects

Figure 6.3

Page 236 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 7: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

The final illustration, in Figure 6.4, shows that it is possible to have the same number of classes as objects. In this case there are 4 different types of shapes, categories or classes on the grid. Since there is only 1 object for each class, we have the situation that you see 4 classes and 4 objects.

Figure 6.4

Chapter VI Using Methods Page 237

Page 8: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

6.3 Using Object Methods

Chapter IV started with the Math class and ended with an introduction of several graphics methods of the Expo class. The primary motivation to introduce graphics programming in Chapter IV was to enhance your understanding of method calls and parameter passing. Program Java0601.java, in Figure 6.5, tries to use the Bank class in the same manner you saw demonstrated with the Math class. The program tries to make deposits to the checking and savings accounts with the checkingDeposit and savingsDeposit methods. After the deposits are made, the getChecking and getSavings methods try to display the balances of the accounts in the Bank class.

With the Math class nobody worried about whose square root you are using, but with a Bank class there is fundamental question about whose checking account or whose savings account? If this all seems weird, do not be concerned. This program will not even compile and the output box shows a variety of error messages indicating serious unhappiness with the programmer.

Figure 6.5

// Java0601.java// This program demonstrates that the methods of a class are not always// accessible, like they were with the <Math> class. In this case an// attempt is made to use methods of the <Bank> class without success.

public class Java0601{

public static void main (String args[]){

System.out.println("\nJAVA0601.JAVA\n");Bank.checkingDeposit(1000.0);Bank.savingsDeposit(5000.0);System.out.println("Checking balance:" + Bank.getChecking());System.out.println("Savings balance: " + Bank.getSavings());System.out.println();

}}

Page 238 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 9: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.5 Continued

The error messages make many statements about non-static methods. This is a logical error message, but right now you do not know about static or non-static methods. At this stage please accept the fact that if you treat object methods like class methods, error messages will be plentiful. When you call class methods you must use the name of the class. Examples would be Math.sqrt or Expo.drawCircle. Object methods are called differently. The main reason Java0601.java did not compile is that it tries to call object methods like class methods.

Program Java0602.java, in Figure 6.6, shows how to use object methods correctly. For each new customer a new Bank object is created, and for convenience sake, we have selected to identify each new object with the name of a bank customer. These new objects are used to call the object methods of the Bank class.

Figure 6.6

// Java0602.java// This program creates two Bank objects, called tom and sue.// Each object stores its own Bank information.

public class Java0602{

public static void main (String args[]){

System.out.println("\nJAVA0602.JAVA\n");Bank tom;tom = new Bank();Bank sue;sue = new Bank();

tom.checkingDeposit(1000.0);tom.savingsDeposit(5000.0);sue.checkingDeposit(1500.0);sue.savingsDeposit (4000.0);

Chapter VI Using Methods Page 239

Page 10: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

System.out.println("Tom's checking balance: " + tom.getChecking());System.out.println("Tom's savings balance: " + tom.getSavings());System.out.println("Sue's checking balance: " + sue.getChecking());System.out.println("Sue's savings balance: " + sue.getSavings());System.out.println();

}}

Figure 6.6 Continued

JAVA0602.JAVA

Tom's checking balance: 1000.0Tom's savings balance: 5000.0Sue's checking balance: 1500.0Sue's savings balance: 4000.0

There are two differences between the Math class and the Bank class. First there are some statements that were never used before with any of the Math sample programs. These are the statements shown in Figure 6.7.

Figure 6.7Bank tom;tom = new Bank();Bank sue;sue = new Bank();

The statements Bank tom; and Bank sue; should not be very surprising. They are identical to the declarations that you have seen in previous chapters. It is a data type followed by a variable identifier format, like int num; the data type is Bank and the variables are tom and sue. This should make sense; however, Bank is more than a simple data type. It is a class. Likewise tom and sue are more than simple variables. They are objects. This is precisely the distinction between a class and an object mentioned in the previous section. A class is a data type and an object is a variable.

Objects are more complicated variables than integer, double or character variables. After you declare some identifier to be an object of a certain class, you also need to make sure that the new object is properly constructed to assume its new duties as an object. The statements tom = new Bank(); and sue = new Bank(); allocate the necessary space in memory for the new object and construct the new objects ready for business. What does it mean to construct a new object? It can mean many things, but right now think of constructing as a combination of allocating space for all the object data and properly initializing each data member

Page 240 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 11: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

of the object. You can think of the constructor method as a special method to open new accounts with the Bank class. The previous program opened two new accounts; one for tom and one for sue. All accounts were opened with a zero balance. After the two objects were constructed with the new operator, calls to checkingDeposit and savingsDeposit added money to the new accounts. The program finished with getChecking and getSavings to display the account balances for Tom and Sue.

It might make sense that two new accounts were opened for Tom and Sue with two new objects, but both accounts started with a zero balance. Objects are usually created with some initial value or values. This is made possible with special methods called constructors. Sometimes objects will have 2 or more constructors. This allows different objects to be created in different situations. This is an example of overloading and it allows program flexibility. You will learn in a later chapter how to write your own classes with methods and constructors. For now, check out program Java0603.java, in Figure 6.8. In the previous program, we had the statement: Bank tom = new Bank(). There were no parameters between the parentheses. The result was that the checking and saving accounts were initialized to zero. Suppose you have your first paycheck in hand, and you plan to use that to open your account. You would not start at zero in this case. That is what this program demonstrates. A different constructor, with 2 parameters, creates the Bank object in a different way. The first parameter is the initial checking account balance and the second parameter is the initial savings account balance.

Figure 6.8

// Java0603.java// This program demonstrates how an object can be constructed with a specified initial// balance in checking and savings. Most Java classes have multiple constructors to// create objects for multiple situations.

public class Java0603{

public static void main (String args[]){

System.out.println("\nJAVA0603.JAVA\n");Bank tom;tom = new Bank(5000.0,10000.0);Bank sue;sue = new Bank(3000.0,15000.0);

System.out.println("Tom's checking balance: " + tom.getChecking());System.out.println("Tom's savings balance: " + tom.getSavings());System.out.println("Sue's checking balance: " + sue.getChecking());System.out.println("Sue's savings balance: " + sue.getSavings());System.out.println();

Chapter VI Using Methods Page 241

Page 12: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

System.out.println("Tom makes a $1000.00 checking deposit");tom.checkingDeposit(1000.0);System.out.println("Tom makes a $2000.00 savings deposit");tom.savingsDeposit(2000.0);System.out.println("Sue makes a $1500.00 checking deposit");sue.checkingDeposit(1500.0);System.out.println("Sue makes a $3000.00 savings deposit");sue.savingsDeposit(3000.0);System.out.println();

System.out.println("Tom's checking balance: " + tom.getChecking());System.out.println("Tom's savings balance: " + tom.getSavings());System.out.println("Sue's checking balance: " + sue.getChecking());System.out.println("Sue's savings balance: " + sue.getSavings());System.out.println();

}}

Figure 6.8 Continued

JAVA0603.JAVA

Tom's checking balance: 5000.0Tom's savings balance: 10000.0Sue's checking balance: 3000.0Sue's savings balance: 15000.0

Tom makes a $1000.00 checking depositTom makes a $2000.00 savings depositSue makes a $1500.00 checking depositSue makes a $3000.00 savings deposit

Tom's checking balance: 6000.0Tom's savings balance: 12000.0Sue's checking balance: 4500.0Sue's savings balance: 18000.0

Page 242 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 13: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Let us think back to Chapter III. You were shown statements that define and initialize variables like:

int x;x = 5;

But then, you were also shown that it is better to define and initialize your variables in one statement like this:

int x = 5;

The same thing applies to creating objects. The previous program first declared an object, and then constructed it, with 2 separate statements:

Bank tom;tom = new Bank(5000.0,10000.0);

As before, it is better to combine these 2 statements into one. We can declare and construct the object in one statement like this:

Bank tom = new Bank(5000.0,10000.0);

Program Java0604.java, in Figure 6.9 demonstrates this concept. It also shows 2 withdrawing methods of the Bank class.

Figure 6.9

// Java0604.java// This program demonstrates how an object can be declared and defined all in one statement.// It also shows the checkingWithdrawal and savingsWithdrawal method.

public class Java0604{

public static void main (String args[]){

System.out.println("\nJAVA0604.JAVA\n");Bank tom = new Bank(5000.0,10000.0);Bank sue = new Bank(3000.0,15000.0);

System.out.println("Tom's checking balance: " + tom.getChecking());System.out.println("Tom's savings balance: " + tom.getSavings());System.out.println("Sue's checking balance: " + sue.getChecking());System.out.println("Sue's savings balance: " + sue.getSavings());System.out.println();

System.out.println("Tom makes a $1000.00 checking withdrawal");tom.checkingWithdrawal(1000.0);System.out.println("Tom makes a $2000.00 savings withdrawal");

Chapter VI Using Methods Page 243

Page 14: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

tom.savingsWithdrawal(2000.0);System.out.println("Sue makes a $1500.00 checking withdrawal");sue.checkingWithdrawal(1500.0);System.out.println("Sue makes a $3000.00 savings withdrawal");sue.savingsWithdrawal(3000.0);System.out.println();

System.out.println("Tom's checking balance: " + tom.getChecking());System.out.println("Tom's savings balance: " + tom.getSavings());System.out.println("Sue's checking balance: " + sue.getChecking());System.out.println("Sue's savings balance: " + sue.getSavings());System.out.println();

}}

Figure 6.9 Continued

JAVA0604.JAVA

Tom's checking balance: 5000.0Tom's savings balance: 10000.0Sue's checking balance: 3000.0Sue's savings balance: 15000.0

Tom makes a $1000.00 checking withdrawalTom makes a $2000.00 savings withdrawalSue makes a $1500.00 checking withdrawalSue makes a $3000.00 savings withdrawal

Tom's checking balance: 4000.0Tom's savings balance: 8000.0Sue's checking balance: 1500.0Sue's savings balance: 12000.0

Page 244 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 15: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

6.4 Using the DecimalFormat Class

We are going to look at a variety of classes (and their methods) in this chapter. Some of the classes have class methods, and others have object methods. Understanding which is which is very important.

We have displayed numbers in several program outputs, but what if we want to make the outputs look more attractive? Maybe we want to line things up a certain way. Java has a clever class, called DecimalFormat, which will do this. With the DecimalFormat class you can control the output appearance of numbers.

We will start the ball rolling with program Java0605.java, in Figure 6.10. This program will "right justify" the output of all the numbers. This appearance is achieved with the format method of the DecimalFormat class. Notice how the output object is constructed with the ("00000") parameter of five zeroes. This means that any number displayed with the format method will be shown with padded leading zeroes for any number with less than five digits. When a number is greater than five digits, the output format is ignored.

Figure 6.10

// Java0605.java// This program demonstrates how to "right justify" integers with an object// of the <DecimalFormat> class and the <format> method.

import java.text.DecimalFormat; // necessary to use DecimalFormat class

public class Java0605{

public static void main (String args[]){

System.out.println("\nJAVA0605.JAVA\n");DecimalFormat output = new DecimalFormat("00000");System.out.println(output.format(1));System.out.println(output.format(12));System.out.println(output.format(123));System.out.println(output.format(1234));System.out.println(output.format(12345));System.out.println(output.format(123456));System.out.println(output.format(1234567));System.out.println();

}}

Chapter VI Using Methods Page 245

Page 16: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.10 Continued

JAVA0605.JAVA

00001000120012301234123451234561234567

We already have a practical use for this. Program Java0606.java, in Figure 6.11, is almost identical to program Java0530.java from the last chapter. This was the program that used a nested loops to display a Times Table. The output did not line up properly because it had a mixture of 1, 2 and 3 digit numbers. It was even mentioned that lining up the columns would be explained in a later chapter. Well, he we are. Using a DecimalFormat of 000 we can add leading zeroes to force all numbers in the table to be 3-digit numbers. This will make the columns line up nicely.

Figure 6.11

// Java0606.java// This program displays a multiplication table with 10 rows and 15 columns.// Do not worry about the fact that the columns do not line up perfectly.// You will learn how to do that in another chapter.

public class Java0606{

public static void main(String args[]){

System.out.println("\nJAVA0606.JAVA\n");

for (int r = 1; r <= 10; r++){

for (int c = 1; c <= 15; c++){

int product = r * c;System.out.print(product + " ");

}System.out.println();

}

System.out.println("\n\n");}

}

Page 246 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 17: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.11 Continued

JAVA0606.JAVA

001 002 003 004 005 006 007 008 009 010 011 012 013 014 015002 004 006 008 010 012 014 016 018 020 022 024 026 028 030003 006 009 012 015 018 021 024 027 030 033 036 039 042 045004 008 012 016 020 024 028 032 036 040 044 048 052 056 060005 010 015 020 025 030 035 040 045 050 055 060 065 070 075006 012 018 024 030 036 042 048 054 060 066 072 078 084 090007 014 021 028 035 042 049 056 063 070 077 084 091 098 105008 016 024 032 040 048 056 064 072 080 088 096 104 112 120009 018 027 036 045 054 063 072 081 090 099 108 117 126 135010 020 030 040 050 060 070 080 090 100 110 120 130 140 150

Program Java0607.java, in Figure 6.12, demonstrates that it is possible to display large numbers with the traditional commas displayed every third digit.

Figure 6.12

// Java0607.java// This program demonstrates how to insert commas in numerical output// with a <DecimalFormat> object.

import java.text.DecimalFormat;

public class Java0607{

public static void main (String args[]){

System.out.println("\nJAVA0607.JAVA\n");DecimalFormat output = new DecimalFormat("0,000,000");System.out.println(output.format(1));System.out.println(output.format(12));System.out.println(output.format(123));System.out.println(output.format(1234));System.out.println(output.format(12345));System.out.println(output.format(123456));System.out.println(output.format(1234567));System.out.println();

}}

Chapter VI Using Methods Page 247

Page 18: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.12 Continued

JAVA0607.JAVA

0,000,0010,000,0120,000,1230,001,2340,012,3450,123,4561,234,567

With the DecimalFormat class it is also possible to add zeroes on the right side of a number after the decimal point. Program Java0608.java, shown in Figure 6.13, displays every number in a standard "US currency" format with a dollar sign and two digits after the decimal point. It also shows the DecimalFormat object does not have to be called output. In this case, money is more appropriate.

Figure 6.13

// Java0608.java// This program demonstrates how to display US currency amounts.// Additionally note how the <format> methods rounds off to the nearest penny.// Also, note that the object does not have to be called "output".

import java.text.DecimalFormat;

public class Java0608{

public static void main (String args[]){

System.out.println("\nJAVA0608.JAVA\n");DecimalFormat money = new DecimalFormat("$0.00");System.out.println(money.format(1));System.out.println(money.format(12.2));System.out.println(money.format(123.32));System.out.println(money.format(1234.432));System.out.println(money.format(12345.543));System.out.println(money.format(123456.654));System.out.println(money.format(1234567.7651));System.out.println();

}}

Page 248 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 19: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.13 Continued

JAVA0608.JAVA

$1.00$12.20$123.32$1234.43$12345.54$123456.65$1234567.77

The next program example in this chapter shows how it is possible to use DecimalFormat objects to round off a real number to a required number of digits beyond the decimal point. The value of PI is used by program Java0609.java, in Figure 6.14, to show an increasing precision that starts with one digit beyond the decimal point up to eight digits.

Figure 6.14

// Java0609.java// This program demonstrates how to control rounding off to a specified// number of digits beyond the decimal point.// It also shows that multiple <DecimalFormat> objects can be in the same program.

import java.text.DecimalFormat;

public class Java0609{

public static void main (String args[]){

System.out.println("\nJAVA0609.JAVA\n");DecimalFormat output1 = new DecimalFormat("0.0");DecimalFormat output2 = new DecimalFormat("0.00");DecimalFormat output3 = new DecimalFormat("0.000");DecimalFormat output4 = new DecimalFormat("0.0000");DecimalFormat output5 = new DecimalFormat("0.00000");DecimalFormat output6 = new DecimalFormat("0.000000");DecimalFormat output7 = new DecimalFormat("0.0000000");DecimalFormat output8 = new DecimalFormat("0.00000000");

System.out.println(Math.PI);System.out.println(output1.format(Math.PI));System.out.println(output2.format(Math.PI));System.out.println(output3.format(Math.PI));System.out.println(output4.format(Math.PI));System.out.println(output5.format(Math.PI));System.out.println(output6.format(Math.PI));System.out.println(output7.format(Math.PI));System.out.println(output8.format(Math.PI));System.out.println();

}}

Chapter VI Using Methods Page 249

Page 20: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.14 Continued

JAVA0609.JAVA

3.1415926535897933.13.143.1423.14163.141593.1415933.14159273.14159265

6.5 Displaying Graphics Characters

We have been displaying text on the screen since chapter II. In this chapter, we just looked at some examples of formatting text output. We can do the same thing on the graphics screen.

Drawing Strings

System.out.println is great, but it only works on the text screen. If you want to display Strings on a graphics screen, you can use the drawString method of the Expo class. drawString requires 4 parameters. As with the other graphics methods of the Expo class, the Graphics object g is the first parameter. Next there is a String parameter. Remember that String literals go in double quotes. drawString also requires 2 int values. This is the X and Y coordinate of the beginning of the String. Program Java0610.java, in Figure 6.15, shows 5 Strings being drawn.

Page 250 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 21: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.15

// Java0610.java// This program demonstrates the <drawString> method.// With <Expo.drawString(g,"Hello World",x,y)>, the string Hello World// will be displayed starting at the [x,y] pixel coordinate.

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

public class Java0610 extends Applet{

public void paint(Graphics g){

Expo.drawString(g,"Top-Left-Hand Corner",40,40);Expo.drawString(g,"Top-Right-Hand Corner",840,40);Expo.drawString(g,"Bottom-Left-Hand Corner",40,640);Expo.drawString(g,"Bottom-Right-Hand Corner",820,640);Expo.drawString(g,"Middle",480,330);

}}

Chapter VI Using Methods Page 251

Page 22: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Displaying Different Graphics Fonts

Suppose you want to display bigger text, or bold text, or italicized text, or text in a different font, or any combination. This is possible with the setFont method of the Expo class. setFont requires 4 parameters. First we have the usual g. The other 3 parameters specify the name, style, and size of the font. Name refers to something like Arial, Courier, TimesRoman, Broadway, Algerian, etc. Style is either Font.PLAIN, Font.BOLD, Font.ITALIC, or Font.BOLD+Font.ITALIC. Size refers to the point size of the font. An example of this would be:

Expo.setFont(g,"TimesRoman",Font.PLAIN,36);

Any drawString command that comes after a setFont statement will be displayed in that font. When no setFont command is used, you get the default font. Program Java0611.java, in Figure 6.16, shows several Strings being drawn in different fonts. The first output shows the default font of Arial-PLAIN-12 point.

Figure 6.16

// Java0611.java// This program introduces the <setFont> method.// setFont requires a Name, Style and Size.// Name is either "Courier","TimesRoman", "Arial", or any other available font.// Style is either Font.PLAIN, Font.BOLD, Font.ITALIC or Font.BOLD+Font.Italic.// Size is the point size value of the Font.

import java.awt.*;

public class Java0611 extends java.applet.Applet{

public void paint(Graphics g){

Expo.drawString(g,"Default Appearance with drawString",20,20);

Expo.setFont(g,"Courier",Font.PLAIN,20);Expo.drawString(g,"Courier 20-point plain font",20,60);

Expo.setFont(g,"Courier",Font.BOLD,20);Expo.drawString(g,"Courier 20-point bold font",20,100);

Expo.setFont(g,"TimesRoman",Font.PLAIN,36);Expo.drawString(g,"Times Roman 36-point plain font",20,180);

Expo.setFont(g,"TimesRoman",Font.ITALIC,36);Expo.drawString(g,"Times Roman 36-point italic font",20,260);

Expo.setFont(g,"Arial",Font.PLAIN,72);Expo.drawString(g,"Arial 72-point plain font",20,400);

Page 252 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 23: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Expo.setFont(g,"Algerian", Font.BOLD+Font.ITALIC, 48);Expo.drawString(g,"Algerian 48-point bold/italic font",20,500);

Expo.setFont(g,"Qwerty",Font.PLAIN,24);Expo.drawString(g,"Arial 24-point plain font substituted for non-existent Qwerty font",20,600);

}}

Figure 6.16 Continued

Chapter VI Using Methods Page 253

Page 24: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

6.6 Drawing Polygons

In chapter IV, you learned how to draw circles, ovals, lines, rectangles, and arcs. What if you want to connect several points to form a polygon? The Expo class has some special methods to handle polygons easily. Polygon means many angles. When you draw polygons you will not need to supply the angles, but you do need to the coordinates of every vertex on the polygon. Polygons can be drawn with three or more coordinate points.

Program Java0612.java, in Figure 6.17, draws a pentagon. You will note the required Graphics object g, followed by five sets of (x,y) coordinates.

Figure 6.17

// Java0612.java// This program demonstrates the <drawPolygon> method.// <drawPolygon> can handle between 3 or more sets of coordinate points to draw// a triangle, quadrilateral, pentagon, hexagon, octagon, or any other polygon.

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

public class Java0612 extends Applet{

public void paint(Graphics g){

Expo.drawPolygon(g,500,100,800,200,600,400,400,400,200,200);}

}

Page 254 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 25: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Think back to the dot-to-dots you did back in first grade. Connecting points is not good enough; you must follow the numbers and connect them in the correct order. Program Java0613.java, in Figure 6.18, shows that the sequence of the coordinate points in the parameter list certainly matters.

Figure 6.18

// Java0613.java// This program demonstrates that the sequence of adding coordinate points// as parameters is significant. The same coordinates of the previous program// are used in a different sequence. The display is very different.

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

public class Java0613 extends Applet{

public void paint(Graphics g){

Expo.drawPolygon(g,400,400,500,100,800,200,200,200,600,400);}

}

Chapter VI Using Methods Page 255

Page 26: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Program Java0614.java, in Figure 6.19, changes the drawPolygon method to the fillPolygon method. The result is a solid pentagon, like the other fill methods.

Figure 6.19

// Java0614.java// This program demonstrates fillPolygon.

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

public class Java0614 extends Applet{

public void paint(Graphics g){

Expo.fillPolygon(g,500,100,800,200,600,400,400,400,200,200);}

}

Page 256 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 27: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Program Java0615.java, in Figure 6.20, shows 2 different fillPolygon commands being used in the same program to draw a boy with a red shirt and blue pants.

Figure 6.20

// Java0615.java// This program fills 2 Polygons to draw a little boy with a red shirt and blue pants.

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

public class Java0615 extends Applet{

public void paint(Graphics g){

Expo.drawCircle(g,500,100,50);Expo.drawLine(g,500,150,500,400);Expo.drawLine(g,500,400,400,600);Expo.drawLine(g,500,400,600,600);Expo.drawLine(g,300,225,700,225);

Expo.setColor(g,Expo.red);Expo.fillPolygon(g,350,200,650,200,650,250,575,250,575,350,425,350,425,250,350,250);

Expo.setColor(g,Expo.blue);Expo.fillPolygon(g,425,375,425,425,350,550,450,600,500,450,550,600,650,550,575,425,575,375);

}}

Chapter VI Using Methods Page 257

Page 28: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

There is something you may have noticed able drawPolygon and fillPolygon that is different from most methods. To understand the difference, let us look at the sqrt and pow methods of the Math class. sqrt always has exactly 1 parameter and pow always has exactly 2 parameters (base & exponent). How many parameters do drawPolygon and fillPolygon have? Cannot really answer that can you? drawPolygon and fillPolygon are designed in a special way to allow you to draw ANY polygon. Unlike the vast majority of methods, number of parameters for these methods is not fixed. Does that mean you can have any number of parameters? Not exactly. There are a couple rules:

Rules for the Number of int Parameters in drawPolygon / fillPolygon

1) There amount of int parameters needs to be an even #.

2) There need to be at least 6 int parameters.

The reason for Rule #1 is that is the fact that the int parameters represent coordinate points. If there were an odd number of int parameters, it would mean there is an x value, without its corresponding y value.

The reason for Rule #2 is the fact that we are drawing polygons which have a minimum of 3 sides. When you draw a 3 sided polygon, which most of us would just call a triangle, you need to specify the locations of the 3 corners. Each of these corners is a coordinate point – with an x and y value. This is where the 6 int values come from.

Over the past few years, I have noticed that one of the most common errors in graphics programs is students using the wrong number of parameters when drawing polygons. To help with this, I have made drawPolygon and fillPolygon a little more user-friendly for the 2014-2015 school year. To demonstrate this we have one final program for this chapter. Program Java0616.java, in Figure 6.21, is almost identical to the previous program. The only difference is that I removed the last int parameter (250) from the first fillPolygon command. This is the one that drew the red shirt. Run the program and see what happens.

Figure 6.21

// Java0616.java// This program demonstrates what happens when <drawPolygon>/<fillPolygon>// is called with an incorrect number of <int> parameters.// Since the <int> parameters represent coordinate points,// the number of <int> parameters must always be even.// Since a polygon must have at least 3 sides,

Page 258 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 29: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

// the number of <int> parameters must be at least 6.// If either condition is not met, a special error message is displayed.

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

public class Java0616 extends Applet{

public void paint(Graphics g){

Expo.drawCircle(g,500,100,50);Expo.drawLine(g,500,150,500,400);Expo.drawLine(g,500,400,400,600);Expo.drawLine(g,500,400,600,600);Expo.drawLine(g,300,225,700,225);

Expo.setColor(g,Expo.red);Expo.fillPolygon(g,350,200,650,200,650,250,575,250,575,350,425,350,425,250,350);

// The last parameter, 250, was removed from the <fillPolygon> command above. // Now the last x value does not have a corresponding y value.

Expo.setColor(g,Expo.blue);Expo.fillPolygon(g,425,375,425,425,350,550,450,600,500,450,550,600,650,550,575,425,575,375);

}}

This program compiles just fine. The error is not detected until later. Figure 6.22 shows the window that pops up when this program is executed. This error window tells you exactly where the error is and what precisely is wrong.

Figure 6.22

After you click OK, you will see the remaining output of the program without the erroneous polygon. This is shown in Figure 6.23 which has the same stick figure as the previous program, minus the messed up red shirt.

Chapter VI Using Methods Page 259

Page 30: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.23

Program Java0617.java, in Figure 6.24, reviews the past few programs. It combines drawPolygon, setFont, and drawString. The program will draw 10 different irregular polygons. setFont and drawString are used to label each of these polygons.

Figure 6.24

// Java0617.java// This program reviews drawPolygon, setFont, and drawString.

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

public class Java0617 extends Applet{

public void paint(Graphics g){

Expo.drawPolygon(g,175,175,250,50,350,200);Expo.drawString(g,"Triangle",225,150); // default font: Name=Arial, Style=PLAIN, Size=12

Expo.drawPolygon(g,400,200,525,200,600,50,475,50);Expo.setFont(g,"Arial",Font.BOLD,16);Expo.drawString(g,"Quadralateral",425,175);

Page 260 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 31: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Expo.drawPolygon(g,650,100,750,50,850,100,850,200,650,200);Expo.setFont(g,"Arial",Font.ITALIC,24);Expo.drawString(g,"Pentagon",700,150);

Expo.drawPolygon(g,25,250,225,250,175,325,225,400,25,400,75,325);Expo.setFont(g,"TimesRoman",Font.PLAIN,24);Expo.drawString(g,"Hexagon",75,375);

Expo.drawPolygon(g,275,250,375,250,475,300,475,400,350,400,350,325,275,325);

Expo.setFont(g,"TimesRoman",Font.BOLD,28);Expo.drawString(g,"Heptagon",300,300);

Expo.drawPolygon(g,525,300,600,250,650,250,725,300,725,350,650,400,600,400,525,350);

Expo.setFont(g,"TimesRoman",Font.BOLD+Font.ITALIC,44);Expo.drawString(g,"Octagon",550,340);

Expo.drawPolygon(g,775,300,800,250,975,250,925,325,975,325,975,400,875,400,825,375,850,325);

Expo.setFont(g,"TimesRoman",Font.ITALIC,36);Expo.drawString(g,"Nonagon",800,300);

Expo.drawPolygon(g,150,500,200,450,250,500,300,450,350,500,350,550,300,600,250,550,200,600,150,550);

Expo.setFont(g,"Algerian",Font.PLAIN,36);Expo.drawString(g,"Decagon",175,540);

Expo.drawPolygon(g,400,450,600,450,575,525,600,525,600,600,550,575,500,600,450,575,400,600, 400,525,425,525);

Expo.setFont(g,"Courier",Font.BOLD,28);Expo.drawString(g,"Undecagon",425,560);

Expo.drawPolygon(g,650,525,700,450,700,525,725,525,725,450,775,450,775,525,800,525,800,450, 850,525,850,600,650,600);

Expo.setFont(g,"Courier",Font.ITALIC,28);Expo.drawString(g,"Dodecagon",675,560);

}}

Chapter VI Using Methods Page 261

Page 32: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.24 Continued

6.7 Drawing Regular PolygonsWe have seen some examples of polygons, but they were not regular polygons. With regular polygons all of the sides are the same length and the measures of all of the angels are equal. It is possible to use the drawPolygon method to draw a regular polygon, but that would either require a lot of trial and error, or a lot of math – specifically trigonometry.

The Expo class has a couple methods to help make this simpler. The first of these methods is drawRegularPolygon. It has similar parameters as drawCircle. Both start with the Graphics object g. Then there is the (x,y) coordinate of the center. After that, there is the radius. Up to this point the circle and the regular polygon are the same. Now drawRegularPolygon has one more parameter to indicate the number of sides or angles in the polygon. Program Java0618.java, in Figure 6.25, demonstrates a pentagon (5 sides), hexagon (6 sides), heptagon (7 sides), octagon (8 sides), nonagon (9 sides) and a decagon (10 sides).

Page 262 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 33: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.25

// Java0618.java// This program demonstrates the drawRegularPolygon of the Expo class.// Regular Polygons are drawn from their center (X,Y) with a certain radius// and a certain number of sides with drawRegularPolygon(g,x,y,radius,numSides).

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

public class Java0618 extends Applet{

public void paint(Graphics g){

Expo.drawRegularPolygon(g,200,170,130,5);Expo.drawRegularPolygon(g,500,170,130,6);Expo.drawRegularPolygon(g,800,170,130,7);Expo.drawRegularPolygon(g,200,490,130,8);Expo.drawRegularPolygon(g,500,490,130,9);Expo.drawRegularPolygon(g,800,490,130,10);

}}

Chapter VI Using Methods Page 263

Page 34: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Program Java0619.java, in Figure 6.26, demonstrates solid regular polygons created with the fillRegularPolygon method of the Expo class.

Figure 6.26

// Java0619.java// This program demonstrates fillRegularPolygon.

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

public class Java0619 extends Applet{

public void paint(Graphics g){

Expo.setColor(g,Expo.blue);Expo.fillRegularPolygon(g,200,170,130,5);Expo.setColor(g,Expo.gold);Expo.fillRegularPolygon(g,500,170,130,6);Expo.setColor(g,Expo.magenta);Expo.fillRegularPolygon(g,800,170,130,7);Expo.setColor(g,Expo.red);Expo.fillRegularPolygon(g,200,490,130,8);Expo.setColor(g,Expo.green);Expo.fillRegularPolygon(g,500,490,130,9);Expo.setColor(g,Expo.purple);Expo.fillRegularPolygon(g,800,490,130,10);

}}

Page 264 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 35: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Stars show up in flags and many other pictures and are essentially a special kind of regular polygon. The Expo also class has a couple star methods, specifically drawStar and fillStar. These are very similar to drawRegularPolygon and fillRegularPolygon and the parameters are practically the same. The only difference is that with the polygon methods, the last parameter indicates the number of sides. With the star methods, the last parameter indicates the number of points. Program Java0620.java, in Figure 6.27, demonstrates both drawStar and fillStar with six stars ranging from 5 points to 10 points.

Figure 6.27

// Java0620.java// This program demonstrates the drawStar and fillStar methods.

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

public class Java0620 extends Applet{

public void paint(Graphics g){

Expo.setColor(g,Expo.blue);Expo.drawStar(g,200,170,130,5);Expo.setColor(g,Expo.gold);Expo.fillStar(g,500,170,130,6);Expo.setColor(g,Expo.magenta);Expo.drawStar(g,800,170,130,7);Expo.setColor(g,Expo.red);Expo.fillStar(g,200,490,130,8);Expo.setColor(g,Expo.green);Expo.drawStar(g,500,490,130,9);Expo.setColor(g,Expo.purple);Expo.fillStar(g,800,490,130,10);

}}

Chapter VI Using Methods Page 265

Page 36: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

6.8 Creating New Colors

The Expo class provides you with 36 different colors. Suppose that is not enough. Let us simply look at the color blue. Yes, there is Expo.blue, Expo.darkBlue, and Expo.lightBlue. But what if you still want more? What if you want the exact shade of blue to match one of your school’s colors? What if you are the romantic type and you want the exact shade of blue to match your girlfriend’s eyes? Java can actually create over 16 million different colors, so any color you can think of is possible. It is like those hardware store commercials where someone brings in toy, points to it, and says, “Can you match this?” Then 10 minutes later he walks out of the hardware store with a gallon of paint that is the exact same color as the toy. Whether you work in the Paint Department of a hardware store, or are writing a graphics program in Computer Science class, the process is pretty much the same – at least logically. (We will not be mixing any actual paint.)

On the computer, you can create any color, by mixing certain amounts of the 3 primary colors: red, green, and blue. Usually when we say this, there are a couple students who have flashbacks to finger-painting in kindergarten. A certain Barney song starts playing in their head,

“When you mix blue and yellow it makes green…”

We are not saying that Barney was wrong. When you work with paint the primary colors are red, yellow, and blue; however, when you with light (as in the light that comes from your computer screen) the primary colors are red, green, and blue. We are right now not going to be concerned with the exact physics of how the computer can produce yellow by mixing red, green, and blue. If you are really curious about that, I suggest you ask your science teacher.

In order to create the new colors, we are going to use the setColor method of the Expo class in a different way. It will still have the usual first parameter, which is the Graphics object g. After that it will have 3 int parameters. The first is a number from between 0 and 255 which indicates how much red you want to use. The second is another number in the [0..255] range which indicates how much green you want to use. The third is yet another number in the [0..255] range which indicates how much blue you want to use. Make sure all 3 numbers are between 0 and 255 or things will simply not work!

Program Java0621.java, in Figure 6.28 only creates 3 new colors. The point here is not to create many colors, but to explain the process necessary to create any color you wish.

Page 266 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 37: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.28

// Java0621.java// This program demonstrates setColor command being used to "create" new colors.// The program will draw the Official Texas Flag with the EXACT shades of red and blue.

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

public class Java0621 extends Applet{

public void paint(Graphics g){

Expo.setColor(g,0,39,104); // Official shade of blue used in the Texas FlagExpo.fillRectangle(g,0,0,325,650);Expo.setColor(g,190,10,47); // Official shade of red used in the Texas FlagExpo.fillRectangle(g,325,325,1000,650);Expo.setColor(g,255,255,255); // Three 255s is the same as color Expo.whiteExpo.fillStar(g,162,325,130,5);

}}

Program Java0622.java, in Figure 6.29 uses three loop structures to iterate through every possible red, green and blue shade that can be created. Each color starts with black and then gradually changes to the most intense red or green or blue.

Chapter VI Using Methods Page 267

Page 38: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.29

// Java0622.java// This program shows all the shades of Red, Green and Blue using the <setColor> method.

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

public class Java0622 extends Applet{

public void paint(Graphics g){

int x = 50;for (int red = 0; red <= 255; red++){

Expo.setColor(g,red,0,0);Expo.drawLine(g,x,0,x,650);x++;

}

x = 350;for (int green = 0; green <= 255; green++){

Expo.setColor(g,0,green,0);Expo.drawLine(g,x,0,x,650);x++;

}

x = 650;for (int blue = 0; blue <= 255;blue++){

Expo.setColor(g,0,0,blue);Expo.drawLine(g,x,0,x,650);x++;

}}

}

Page 268 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 39: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

If you look closely at this output, it almost looks like 3 cylindrical pillars. The brighter colors on one side and the darker colors on the other create a shading effect similar to what many artists use. Shading – if done properly – can give a 2-D object a 3-D appearance.

6.9 Creating Random Numbers

Generating random values is a surprisingly big deal in many ways. Billions of dollars are spent on advertising, which is largely based on the surveys of a population sample picked at random. Politicians are continuously "polling" their constituents, which need random values. Video games have become big business and no video game can survive without a true random behavior of events. So how do we make something random? Java has a built-in random method, which belongs to the Math class, but it is quite complicated to use. The Expo class has its own random method, which is designed to be easier to use.

Program Java0623.java, in Figure 6.30, displays 5 random numbers between 1 and 100. Do not be surprised if your output does not match ours. The program displays random numbers. Every time the program is executed, the output will be different.

Figure 6.30

// Java0623.java// This program uses the <random> method of the Expo class 5 times// to create 5 random numbers between 1 and 100.

public class Java0623{

public static void main (String args[]){

System.out.println("\nJAVA0623.JAVA\n");System.out.println(Expo.random(1,100));System.out.println(Expo.random(1,100));System.out.println(Expo.random(1,100));System.out.println(Expo.random(1,100));System.out.println(Expo.random(1,100));

}}

Chapter VI Using Methods Page 269

Page 40: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.30 Continued

Java0623.java Output #1

JAVA0623.JAVA

837877152

Java0623.java Output #2

JAVA0623.JAVA

5634743648

Program Java0624.java, in Figure 6.31, displays 5 random numbers – like the previous program – however; in this program the user enters the minimum number and the maximum number.

Figure 6.31

// Java0624.java// This program allows the user to specify the range of random numbers.

public class Java0624{

public static void main (String args[]){

System.out.println("\nJAVA0624.JAVA\n");System.out.print("Enter the smallest number you want. --> ");int minimum = Expo.enterInt();System.out.print("Enter the largest number you want. --> ");int maximum = Expo.enterInt();System.out.println();System.out.println(Expo.random(minimum,maximum));System.out.println(Expo.random(minimum,maximum));System.out.println(Expo.random(minimum,maximum));System.out.println(Expo.random(minimum,maximum));System.out.println(Expo.random(minimum,maximum));System.out.println();

}}

Page 270 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 41: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.31 Continued Java0624.java Output #1

JAVA0624.JAVA

Enter the smallest number you want. --> 10Enter the largest number you want. --> 99

4182233284

Java0624.java Output #2

JAVA0624.JAVA

Enter the smallest number you want. --> 1000Enter the largest number you want. --> 9999

78134110719297855656

6.10 Using Random Numbers withGraphics

There are two Java concepts you have learned that combine very nicely. You have learned to create a variety of graphic images with methods of the Expo class. In this chapter you have also learned how to generate random numbers of a specific range. When you combine these two features, you can create some interesting programs.Random number generation works well with graphics. Program Java0625.java, in Figure 6.32 displays 3 lines. The first 2 are black and have fixed number

Chapter VI Using Methods Page 271

Page 42: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

parameters. These 2 lines will always be the same. The third line is red and has 4 integer variable parameters – and each of those integer variables stores a random integer value. This line will be different with each execution. Note that the range of the random integers is intentionally selected to stay within the coordinate range of the applet window.

Figure 6.32

// Java0625.java// This program first displays two lines in a fixed location.// This is followed by generating four random values, which are// used to draw a third line in a random location.

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

public class Java0625 extends Applet{

public void paint(Graphics g){

Expo.drawLine(g,500,0,500,649); Expo.drawLine(g,0,325,999,325); int x1 = Expo.random(0,999); int y1 = Expo.random(0,649); int x2 = Expo.random(0,999); int y2 = Expo.random(0,649); Expo.setColor(g,Color.red); Expo.drawLine(g,x1,y1,x2,y2);

}}

Figure 6.32 Continued

Page 272 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 43: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

The same concept is shown in the next program. Program Java0626.java, in Figure 6.33, displays 2 circles. The first is black and has a fixed center coordinate and a fixed radius length. This circle will always be the same. The second circle is red and uses three random integer values which determine the center (x,y) coordinate and the length of the radius. Not only will this circle have a random location on the screen, it will also have a random size.Figure 6.33

Chapter VI Using Methods Page 273

Page 44: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

// Java0626.java// This program displays a circle in a fixed location with a fixed size.// Two random values are generated for the center location of the circle// and a third random value is used for the radius of the circle.

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

public class Java0626 extends Applet{

public void paint(Graphics g){

Expo.drawCircle(g,500,325,250); int x = Expo.random(150,850); int y = Expo.random(150,500); int radius = Expo.random(10,150); Expo.setColor(g,Expo.red); Expo.drawCircle(g,x,y,radius);

}}

Figure 6.33 Continued

Page 274 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 45: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Chapter VI Using Methods Page 275

Page 46: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Now we will add loops to the mix. Program Java0627.java, in Figure 6.34, generates 1000 random lines. These lines are all black.

Figure 6.34

// Java0627.java// This program displays 1000 random lines.

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

public class Java0627 extends Applet{

public void paint(Graphics g){

for (int k = 1; k <= 1000; k++){

int x1 = Expo.random(0,1000);int y1 = Expo.random(0,650);int x2 = Expo.random(0,1000);int y2 = Expo.random(0,650);Expo.drawLine(g,x1,y1,x2,y2);

}}

}

Page 276 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 47: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Random Colors

The idea of a random color may seem a bit strange. Random numbers, OK; but random colors… how is that possible? Remember that colors can be created by using 3 int values between 0 and 255. Well, what if these 3 values are random. Program Java0628.java, in Figure 6.35, generates a random red, green and blue value, each between 0 and 255. When these random amounts of colors are mixed the result is a random color. These random colors are used to draw 1000 random solid circles. Every circle has a radius of 50.

Figure 6.35

// Java0628.java// This program displays 1000 random colored solid circles.// All circles have a radius of 50.

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

public class Java0628 extends Applet{

public void paint(Graphics g){

Expo.setColor(g,Expo.red);Expo.drawThickRectangle(g,0,0,1000,650,100);Expo.setColor(g,Expo.blue);

for (int k = 1; k <= 1000; k++){

int x = Expo.random(0,1000);int y = Expo.random(0,650);

int red = Expo.random(0,255);int green = Expo.random(0,255);int blue = Expo.random(0,255);Expo.setColor(g,red,green,blue);Expo.fillCircle(g,x,y,50);

}}

}

Chapter VI Using Methods Page 277

Page 48: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.35 Continued

Program Java0629.java, in Figure 6.36, is almost the same as the previous program. The one difference is now the radius is random as well.

Figure 6.36// Java0629.java// This program displays 1000 random colored solid circles, with random radii.

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

public class Java0629 extends Applet{

public void paint(Graphics g){

for (int k = 1; k <= 1000; k++){

int x = Expo.random(0,1000);int y = Expo.random(0,650);int red = Expo.random(0,255);int green = Expo.random(0,255);int blue = Expo.random(0,255);int radius = Expo.random(1,100);Expo.setColor(g,red,green,blue);Expo.fillCircle(g,x,y,radius);

}}

}

Page 278 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 49: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

Figure 6.36 Continued

Program Java0630.java, in Figure 6.37, changes from circles to regular polygons. It displays 1000 regular polygons – which all turn out to be equilateral triangles. Several things are random in this program. The values of x and y are random, which means that every regular polygon has a random location. The radius is random, so every regular polygon has a random size. Even the color is random, although in this program random colors are created with a single setRandomColor command. The one thing that is not random is the number of sides. It is always 3. This is why every random polygon is an equilateral triangle.

Figure 6.37

// Java0630.java// This program displays 1000 randomly colored equilateral triangles.// Creating random colors is also simplified with the setRandomColor method.

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

public class Java0630 extends Applet{

public void paint(Graphics g){

for (int k = 1; k <= 1000; k++){

int x = Expo.random(0,1000);

Chapter VI Using Methods Page 279

Page 50: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

int y = Expo.random(0,650);int radius = Expo.random(1,100);int sides = 3;Expo.setRandomColor(g);Expo.fillRegularPolygon(g,x,y,radius,sides);

}}

}

Figure 6.37 Continued

Program Java0631.java, in Figure 6.38, is the last program. The one difference between this program and the previous program is now the number of sides is random. This means we will not only see equilateral triangles, we will also see squares, regular pentagons, regular hexagons, all the way up to regular decagons.

Figure 6.38

// Java0631.java// This program displays 1000 randomly colored polygons with a random # of sides.

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

Page 280 Exposure Java 2015, Pre-AP®CS Edition 05-19-15

Page 51: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

public class Java0631 extends Applet{

public void paint(Graphics g){

for (int k = 1; k <= 1000; k++){

int x = Expo.random(0,1000);int y = Expo.random(0,650);int radius = Expo.random(1,100);int sides = Expo.random(3,10);Expo.setRandomColor(g);Expo.fillRegularPolygon(g,x,y,radius,sides);

}}

}

Figure 6.38 Continued

Chapter VI Using Methods Page 281

Page 52: Chapter I - vernonmath.comvernonmath.com/.../Text06-ClassAndObjectMethods.docx  · Web viewIn high school there may be a French class, a Geometry class, an Art class and a Computer

6.11 Summary

This chapter began by explaining the difference between class methods and object methods. The Math class and the Expo class are examples of classes that have class methods. With a class method, the name of the class is used to call the method. Examples would be:

System.out.println( Math.sqrt(100) ); // displays the square root of 100 which is 10

System.out.println( Expo.random(100,200) ); // displays a random number between 100 and 200

The Bank class and the DecimalFormat class are examples of classes with object methods. With an object method, an object must be created in order to call the method. Examples would be:

Bank tom = new Bank(); // create a Bank object called tomTom.checkingDeposite(1000); // deposit $1000 in tom’s checking account

DecimalFormat money = new DecimalFormat(“$0.00”);System.out.println(money.format(765.4321)); // displays $765.43

Output format can be controlled with methods of the DecimalFormat class. With DecimalFormat and the format method it is possible to format the output of a number. You can pad zeroes in front and behind a number. It is also possible to insert commas and round off a real number to a desired number of digits beyond the decimal point or add dollar signs as the example above shows.

Several new methods from the Expo class were introduced. setFont is used to manipulate the size and style of graphics fonts. setColor can be used not only for existing colors, but to create new colors as well. The Expo class also has methods to draw regular and irregular polygons, as well as stars.

Random Numbers make computer simulations and video games possible. While the Math class has a random method, it is complicated to use. The Expo class also has a random method that is designed to be easy to use. You just specify the smallest and largest number you want and it gives you a random number within that range. Once the random values are obtained, they can be used in many different ways including creating random colors, drawing shapes in random locations, drawing shapes with a random size, drawing polygons with a random number of side, or any combination thereof.

Page 282 Exposure Java 2015, Pre-AP®CS Edition 05-19-15