My first in java book

Page 1


Dedication To Nanay and Tatay

2


Foreword There are many good java books available that you could buy. My First in Java does not intend to compete with those books. If you are new to programming and don’t know which book to buy for your skills development, this book is a good start before acquiring other specialized books later in java. The author avoided lengthy discussion of theories. It is on his belief that student must be presented with working examples to learn java faster. No prior knowledge in programming is required to understand the concept of the book. Consideration was given to readers who may have problem in understanding the written text presented in the tutorial. YouTube video links are also included on some chapter if the student opted to learn using videos. Still, the book is necessary if the student intends to copy and paste the programs and see how it works. Not all topics on this book are presented with videos. Still, a good grasp of the concept must be understood with the use of the written texts. Considerable simulation examples were also discussed in the book. The author believes student must learn to read programs what other programmers did to appreciate the various approaches in solving programming algorithms. Solution of simulations is handwritten on video presentation. Proceed on the lessons chapter by chapter. The student may be lost on a chapter if one intends to skip previous chapters since concepts are discussed in cumulative order. It is suggested that the student answer the exercises. The exercises may validate the level of understanding the student got on each chapter. Sample solutions on selected numbers are included at the end of the book. Object-oriented programming is not yet discussed on this book. Though java is an OOP language, the author believes OOP concepts are too broad or too early to discuss for students who are just starting to learn programming. The ultimate purpose of the book is to help anyone who wants to pursue a profession in programming but has a hard time in understanding the text of other books or wishes to repeat the lecture of the teacher who conducted the programming course. This book is for you.

3


About the Author Jeremias C. Esperanza is a Computer Science professor currently teaching at New Era University (NEU), Quezon City, Philippines. He had also stint teaching at Jose Rizal University (JRU) and Asia Pacific College. Subjects he teaches include Introduction to Programming, Object-Oriented Programming, Database Management Systems, Systems Analysis and Design, Digital Design, and Software Engineering. Teaching profession spans 10 years now from the time he left the industry to pursue an academe post. He worked as Administrative Specialist at IBM Philippines, Inc. and served as a Technical Support Engineer at ETSI Technologies, Inc. (A Siemens Nokia joint ventured company) for ten years. He was a Database Marketing Analyst for a year at OSRP (a PCMall.com company) and as Analyst at Business Intelligence Group of eTelecare Global Solutions for another couple of years. As database professional, he is an IBM DB2 Academic Associate Certified. A good grasp of Business Intelligence (BI) using IBM Cognos is also included as one of his skills. He currently pursues his doctorate degree in Information Technology; holds a master's degree in Education major in Educational Management and a bachelor's degree in Computer Engineering. Most of his developed instructional text have now reached a total of 195,127 views on Scridb.com. YouTube instructional videos have reached 177. 083 views. He is one of Yahoo!Contributor Network writers who submits articles life of general interest. As a registered professional teacher, he loves inspiring people to experience their unique full potential.

4


Table of Contents Dedication.......................................................................................................................2 Foreword.........................................................................................................................3 About the Author.............................................................................................................4 Chapter 2: JAVA FIRST PROGRAM ...........................................................................15 Hello, world! .............................................................................................................15 COMMENT, NEW LINE AND TAB CHARACTERS .............................................16 CONCATENATION OF TEXT ................................................................................17 EXERCISE 2.............................................................................................................17 Chapter 3: NAMING IDENTIFIERS AND DATA TYPES ..........................................19 Naming Identifiers/Variables ..................................................................................... 19 Naming Conventions .................................................................................................20 Data Types ................................................................................................................20 EXERCISE 3.............................................................................................................21 Chapter 4: Input and Output Statements........................................................................22 Simple Input/Output ..................................................................................................22 Arithmetic Operators .................................................................................................26 Order of Precedence ..................................................................................................27 Assignment Operator.................................................................................................29 Extended Assignment Operator .................................................................................29 Increment/Decrement Operator..................................................................................29 Working with Arithmetic Operations .........................................................................30 Format double value with Two Decimal places...................................................... 35 EXERCISE 4.............................................................................................................36 Chapter 5: SELECTION STRUCTURE ........................................................................39 THE if STATEMENT ............................................................................................... 39 THE if-else STATEMENT ........................................................................................ 41 Nested if-else statement ............................................................................................. 42 Logical Operators......................................................................................................43 THE switch/case STATEMENT................................................................................44 SIMULATE: Determine the output...........................................................................54 EXERCISE 5.............................................................................................................59 Chapter 6: CONTROL STRUCTURES........................................................................64 The while statement ...................................................................................................64 The do – while statement ........................................................................................... 66 The for statement.......................................................................................................68 Indefinite Loop..........................................................................................................73 Loop within a loop ....................................................................................................76 EXERCISE 6.............................................................................................................82 Chapter 7: Methods .......................................................................................................90 Anatomy of a Method Declaration.............................................................................91 Coffee Vendo Machine: An Example .......................................................................92 More on Methods Passed-by-Value ...........................................................................98 Simulate: Determine the output............................................................................... 101 EXERCISE 7........................................................................................................... 104 Chapter 8: ARRAYS ................................................................................................... 110

5


Declare an Array variable ........................................................................................ 111 Assign Value on Array Element............................................................................... 111 Array: A working Example...................................................................................... 112 Arrays with Numeric Data Types............................................................................. 113 Multi-Dimensional Array ........................................................................................ 117 Multi-dimensional Declaration and Assignment of Values....................................... 118 Working Example of Two-dimensional Array ......................................................... 120 Simulate: Determine the output............................................................................... 125 EXERCISE 8........................................................................................................... 131 SOLUTION TO SELECTED SAMPLE EXERCISES................................................. 137

6


CHAPTER 1 INSTALLATION OF JAVA COMPILER AND ECLIPSE IDE At the end of this chapter, you will be able to: 

Install java compiler



Install Eclipse IDE

Before we could write our first java programs, we need to install our java compiler that will convert our source program into an object file that a machine can understand. An Integrated Development Environment (IDE) is a software tool used by developers in writing, compiling, debugging, and running their programs. This is where Eclipse IDE is known for. The following installation will guide us on how to install java compiler and Eclipse IDE on our computer.

Installing Java Compiler for Windows 1. Go to your browser. 2. Visit http://google.com 3. Type in the google search box: java jdk. 4. Click Java SE Downloads

Figure C1. 1

7


Figure C1. 2

4. Click the latest release. On this case it is the Java Platform (JDK) 7u6. (see Figure C1.2). 5. Click the Accept License Agreement.

Figure C1. 3

6. Underneath select the appropriate java compiler suited for your OS. On this case, we choose Windows X86 for the 16-bit Windows 7 OS.

8


Figure C1. 4

6. Wait for the download to complete. Double click the downloaded file (see Figure C1.5).

Figure C1. 5

7. On Windows 7 you will be prompted if the installer is allowed to make changes. Just click yes. 8. You will be prompted on the installation procedure. Accept the default settings. Just click Next.

9


Figure C1. 6

Figure C1. 7

8. This is the last window when the installation is completed. Click Finish. See the video tutorial version

10


Figure C1. 8

Installing Eclipse IDE 1. Visit http://www.eclipse.org/downloads/

Figure C1. 9

2. Depending on your computer OS, click the corresponding link (normally, XP is Windows 32 bit, Windows 7 is 32 or 64 bit). On my case, I’m using Windows 7, I will click Eclipse Classic 3.7.2 Windows 32 bit. Skip 3 if you are running under Windows OS. 3. If you are running a different OS (Linux or Mac OS), you may select it on the dropdown box. Just the same, click the bit version your OS supports.

11


Figure C1. 10

4. You will be prompted to select the mirror location where downloads will come from. Click the suggested default site (green down arrow). Depending on the speed of your modem, this may take a while. Wait for the download to complete.

Figure C1. 11

5. Double click the zip file to begin extraction of eclipse.

Figure C1. 12

6. Click the Extract To commence.

12


Figure C1. 13

7. Select (C:) Local Disk as the destination of our extraction. Click OK.

Figure C1. 14

8. After completing the extraction of the file, close the Winzip program. 9. Click. Start | My Computer 10. Double click (C:) Local Disk.

13


11. Double Click the Eclipse folder. 12. Right-click the Eclipse icon and Send To | Desktop to create a shortcut.

Figure C1. 15

See the video tutorial version

14


Chapter 2: JAVA FIRST PROGRAM At the end of this chapter, you will be able to:   

Write your first sets of java programs; Familiarize with the terminator symbol semicolon; Use comments, new line and tab characters;

Hello, world! We will write our first program in java. Below is the code that displays message “Hello, world!”. package javaPackage; public class Hello { public static void main (String[] args) { System.out.println("Hello, world!"); } } The title of our program is Hello. From now on, every time we create our java program, the first letter of the program name should be in capital letter. public class are reserved words used by programmers to tell the java compiler the name of the program. Again, every time we create a new java program we will use these words before our program name. Opening and closing curly braces are used to denote the beginning and ending of a block. That’s why you could see an opening brace after the first line of the program. You will notice that corresponding partner of the first opening brace is aligned with the closing brace at the last line of the program. Though alignment of braces is not required, it improves readability if program is written this way because as the program becomes longer, we will be working with sets of opening and closing braces. It is harder to trace and debug errors if program is not written this way. Next is public static void main(String[] args). This line is the main program or main method where the java compiler seeks first as the program executes. Never mind if you don’t understand yet the meaning of this line. From now on, every time we create program, we will use this line. You would again notice that the main method/program is enclosed with curly braces. This is required to signify the start and end of the main method. System.out.println() is a command that we use to tell the compiler to display the message Hello, world!. All literal output must be enclosed with double quotes. That is why on the statement you would see “Hello, world!” is enclosed. At the end of the line we have a

15


semicolon (;) that terminates the statement. Every java statement must be terminated by semicolon. See the video tutorial version of Java First Program

COMMENT, NEW LINE AND TAB CHARACTERS Suppose an output in our program requires like this: Hello, world! Java language is Programming

awesome! is fun!

How do you work out on with the use of System.out.print() command? Now, let us create another program named HelloAgain. This time we make use of the newline (\n) and tab (\t) characters. package javaPackage; public class HelloAgain { public static void main(String[] args) { System.out.println("Hello, world!"); // Use double backslash to comment out System.out.print("Java\tlanguage\tis\tawesome!\n"); System.out.println("\t\tProgramming\t\tis\tfun!"); // This is neat! } } We use double forward slash (//) to insert a comment with your program. It is a good practice to place a comment once in a while to your program so the reader (or even you) may be guided on what you want to achieve on this part. You could also place this after a valid java command (// This is neat!). Comments are skipped by the java compiler. \t denotes tab character. This means a tab space will be placed in between before printing the next set of strings/texts. \n is a newline character that tells the compiler to proceed to the next line. You may have noticed that we used System.out.print() instead of System.out.println() after printing the Hello, world! line. This produces the same effect since we have \n within the text.

16


CONCATENATION OF TEXT Now, here’s an extra challenge! How do you display the same output with the use of one System.out.println() only in the program? Here’s the revised HelloAgain program: package javaPackage; public class HelloAgain { public static void main(String[] args) { // This program uses only ONE System.out.println System.out.println("Hello, world!\n" + "Java\tlanguage\tis\tawesome!\n" + "\tProgramming\t\tis\tfun!"); } } Instead of issuing another System.out.println(), we concatenated/joined the text with plus (+) operator . You could type the whole System.out.println() statement in one line but it will make our codes longer. The compiler ignores white spaces so there is no problem if we move the concatenated text to the next line. This kind of coding practice increases also the readability of our program. See the video tutorial version

EXERCISE 2 1. Write a java program Dream that outputs the following using 4 System.out.println() statements: This is my quest! To follow the star No matter how hopeless No matter how far 2. Create a java program PriceTag that outputs the following using 3 System.out.print() statements ONLY: Its not about the money, money, money We don't need your money, money, money We just wanna make the world dance, Forget about the Price Tag

17


3. Formulate a java program Victor that outputs the following lines using 1 System.out.print() ONLY: Life's battles don't always go To the stronger or faster man. But sooner or later, the man who wins Is the man who thinks he can.

18


Chapter 3: NAMING IDENTIFIERS AND DATA TYPES At the end of this chapter, you are able to:     

Assign variable/identifier name correctly; Follow proper naming conventions; Derive a camelized form on two-word or more variable name; Know the different data types used in java; Declare variable/identifier’s data types.

Naming Identifiers/Variables Think identifiers/variables as containers used by java program whenever it performs calculation. Identifiers/variables hold the value for you and you easily use it whether to perform computation or show its value. Since variables are programmer-defined (programmer has freedom to name it), there are rules we need to remember when using it. These are: 1. Variables should start either by letters(not numbers) or special symbol such as underscore (_) or dollar sign($). You can use numbers in between the name of the variable. Example: name $money _counter interest2Pay amount3 2. No space is allowed between a two-word (or more) variable name. We may use a camelized form to improve readability. You can use also underscore in between words if you want the identifier separated.

Table 3.1 3. Do not use java reserved words. Compiler error will occur if you use it. Example of reserved words you can’t used are:

19


int

double

System

class

public

main

Naming Conventions On this book we follow a certain naming convention. Naming convention is the preference format used by developers so they can easily understand the meaning of the codes. These are: 1. Use camelized form. If you need to use two-word (or more) variable, the second( or succedding) word starts with capital letter. This improves readability. For example:

Table 3.2 2. Use small letter at the start of variable name. Variables should start in small letter to distinguish our variables from other classes used by java. Professional programmers use capital letter to signify the name of the program(class). Adhere to this practice so other will respect the way you code.

Data Types Our identifier/variables must be defined at the start of any java program. This is one way of telling the java compiler that you have set of containers(variables) that you may use in the execution of the program. Just like any container, you need to define or tell the capacity of how much or what it can hold. If your variable is age, you are expecting a whole number as its value. Therefore, the data type you will used i integer or int. This is how you declare it: int age; Variable name such as weight needs to show its fractional value. Data type you need to use here is either float or double: float weight; double heavyweight; The following table is summary of data types used in this book. Boolean, char will be explained as we use it in actual program.

20


Table 3.3

We will use special class String that will hold value that is not designed for computation but holds text content itself. Example of these is name, product, and message. We would declare it this way: String name; String product; String message; See the video tutorial version

EXERCISE 3 I. TRUE OR FALSE: Determine if the following is valid identifier/variable name. 1. 2. 3. 4. 5. 6. 7. 8.

sales course3 4TheWin _ctr quantity sold double static true

II. Declare identifier at the start of the program if it holds a certain value.

21


1. price holds 10.25 dollars. 2. tray holds 10 eggs. 3. distanceCovered accumulate 4.9 km. 4. titleOfTheBook is “7 Habits of Highly Effective People”.

Chapter 4: Input and Output Statements Upon completion of this chapter you should able to:         

Define and use variables/identifiers; Accept input entry and display output results; Determine the arithmetic operator symbols used in java; Write the correct java formula format; Evaluate arithmetic operations following the order of precedence; Express java expression in an alternative format when working with assignment operator; Express increment and decrement operators in a variable. Concatenate string and numbers;. Format decimal numbers with commas and two decimal-point values.

Simple Input/Output We have discussed so far how to name our identifiers/variables that we may use on our program. Now, we are ready to work on our another program. Consider that we have the following problem: Design java program NameAndAge that user accepts name and age entry and outputs it at the end of the program. Sample Input/Output: Enter name: John Enter age: 18 Your name is John You are 18 years old The name of the java program is NameAndAge. As we follow the pattern set on our first java program we will have the following code as our starter format: package javaPackage; public class NameAndAge { public static void main(String[] args) {

22


} } Next, we will prompt the user to enter name. Thus, we will have to set text on where the user will type in the name. We have : package javaPackage; public class NameAndAge { public static void main(String[] args) { System.out.print("Enter name: "); } }

On this case we have used System.out.print() because we want our cursor (the blinking prompt that awaits input) to be after the name text. To make our cursor awaits user to input name, we will use a special java class program that does this: the Scanner class. In order to use the Scanner class, we need to include or import this piece of code from the start of our program. To do this, we type: import java.util.Scanner; To make use of what we have included on our program, we need to declare it with the following code: Scanner input = new Scanner(System.in); We instantiate an object name input (programmer-defined) as a container that will handle all our input activities on the program. System.in signifies that Scanner will await input from prompt. As you will notice on the above two lines of code, all statements are terminated by semicolon. Java statements must be terminated by this symbol. Next we declare a container name as a repository data that will store any name entered by user. Take note that name is declared as String data type. So far, our program is updated like this: package javaPackage; import java.util.Scanner; public class NameAndAge { public static void main(String[] args) {

23


Scanner input = new Scanner(System.in); String name; System.out.print("Enter name: "); } } Now, to prompt the user to enter name, we use our identifier/variable name to store whatever the user enters. The following line handles this job: name = input.nextLine(); The input.nextLine() suddenly pauses the cursor and accepts anything that is typed-in before hitting the enter key. Whatever entered on that line will be stored/placed on the variable name. So our code is updated this way: package javaPackage; import java.util.Scanner; public class NameAndAge { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name; System.out.print("Enter name: "); name = input.nextLine(); } } We do that same on age. We declare first a variable age as integer on the upper part of the program along with input and name. Prompt the user to enter the age; store whatever number into the variable age. Thus, we have now: package javaPackage; import java.util.Scanner; public class NameAndAge { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name; int age; System.out.print("Enter name: "); name = input.nextLine();

24


System.out.print("Enter age: "); age = input.nextInt(); } } input.nextInt() was used because the data type of age is an integer. The line converts any number into an integer value. Next, we are now ready to display whatever entries the user typed-in on the prompts. We used the following lines: System.out.println(); System.out.println(“Your name is “+ name); System.out.println(“You are “ + age + “ years old”); We used the first System.out.println() as a command to advance one line as a separator for the output lines. As you notice, we have used System.out.println() instead of System.out.print(). What does this thing denote? The cursor will proceed to the next line AFTER printing/displaying the output enclosed within the parenthesis. The literal output Your name is is enclosed with double quotes and is concatenated by + symbol with whatever value the name has on its content. Same is true for displaying the output for age. We have age concatenated with the literals You are and years old. Take note that age is not enclosed with double quotes. It means that the word age is not displayed literally but by whatever value it has on its content. As with our final codes we have: package javaPackage; import java.util.Scanner; public class NameAndAge { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name; int age; System.out.print("Enter name: "); name = input.nextLine(); System.out.print("Enter age: "); age = input.nextInt();

25


System.out.println(); System.out.println("Your name is " + name); System.out.println("You are " + age + " years old"); } } See the video tutorial version

Arithmetic Operators Java performs mathematical operations. It uses almost the same set of operators that denotes calculations you want to perform. The following is the list of operators used by java: Operator/Symbol * / % + -

Arithmetic Operation Multiplication Division Modulus (remainder) Addition Subtraction

Table 4.1 Arithmetic Operators So, if we write the formula in physics Speed = Distance Time we write in java speed = distance / time; To get the percentage of base amount, we have: Percentage = Baseâ—? Rate Thus, in java this is percentage = base * rate We use asterisk (*) to denote multiplication in java. How about if we would like to convert algebraic expression in java? With the given example:

26


y = x2 + 2x + 4 For now, though java has built-in packages that compute exponential value, we would write the above formula in the following way: y = x * x + 2 * x + 4;

Order of Precedence Java does not violate the rule in mathematical operation when working on multiple operators. It follows the same hierarchy in performing mathematical operations. The given table shows this: Symbol () *, /, % +, -

Operations Grouping of expression

Remarks Expression in parenthesis is evaluated first. Multiplication, Division, Enjoys same hierarchy; evaluated Modulus (remainder) whichever comes first from left to right. Addition, Subtraction Enjoys same hierarchy evaluated whichever comes first from left to right. Table 4.2 Order of Precedence

If we have a given formula: Net Price = Sale Price – Sale Price ● Discount Rate Assuming the value of sale price is 1000 and discount rate is 10%, java evaluates: netPrice= salePrice – salePrice*discountRate; netPrice = 1000 – 1000* 0.1 netPrice = 1000 – 100 netPrice = 900 The given expression with x = 2: y = (x + 1)2 – (x – 4) + 2x 4 is written and evaluated in java as : y = (x+1)*(x+1) – (x-4) + 2*x/4; y = (2+1)*(2+1) – (2-4) + 2*2/4 y = 3*3 – (-2) + 2*2/4 y = 9-(-2)+ 2*2/4 y = 9 –(-2) + 4/4 y = 9-(-2) +1

27


y = 9+2+1 y = 9+2+1 y =11+1 y = 12

28


Assignment Operator We use the equal sign (=) operator to assign value to a variable. Below is an example of how a given pseudo-code (not real code) is expressed in java: Pseudo-code Assign 10 to x. Deduct 3 from y.

Add 1 to z. Multiply x with y and assign product to z

Java format x = 10;

Explanation Assign the numerical value 10 to x. x now has value 10. y = y – 3; Get the difference first from the left of the equation (y – 3) and assign/overwrite the result to variable y. z = z + 1; Add the left of the equation ( z + 1) and assign/overwrite its sum to variable z. z=x*y Multiple the values of x and y and place/assign its product to variable z. Table 4.3 Assignment Operator

Take note that the arithmetic operator and equal sign should not have a space in between.

Extended Assignment Operator Another format can be used as a shortcut when working with java expression. We could use this as an alternative to make our code small. Java Expression Alternative form (is the same as) y = x + 1; x += 1; y= y – 3; y -= 3; a = a / 5; a /= 5; b = b % 2; b %= 2; c = c * 7; c *= 7; totalPrice = totalPrice – totalPrice*discount; totalPrice -= totalPrice*discount; Table 4.4 Alternative Form of Assignment

Increment/Decrement Operator When you encounter the word increment or decrement, it means that you need to increase or decrease the variable by 1. This is written this way: x++; y--

// This is the same as x = x +1; or x += 1; // This is the same as y=y – 1; or y -= 1;

We will use most of this when working mostly on looping statements.

29


See the video tutorial version

Working with Arithmetic Operations Our previous example showed only how to output input entries. How about if we are concern displaying computed values? Consider the following problem: Design java program NetPrice that computes the net price of a given product. Impose a 10% discount on total price. Sample Input/Output: Enter product: iPhone 4s Enter unit price: 399.97 Enter quantity: 20 The product is iPhone 4s Total price is 7,999.40 dollars Discount is 799.94 dollars Net Price is 7,199.46 dollars Let us start coding our program with the basics. We do first the inputting of data. We will have the following code as a starter: package javaPackage; import java.util.Scanner; public class NetPrice { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter product: "); System.out.print("Enter unit price: "); System.out.print("Enter quantity: "); } } Just like with our previous example, we have used here the Scanner class utility that will handle our entries for the program. We used System.out.print() because we want our cursor to be placed after the colon of each prompt.

30


Next we declare an identifier or variable that will hold the value of each entry that we will have on the program. package javaPackage; import java.util.Scanner; public class NetPrice { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Initialize our variables that will handle our inputs String product = ""; // null value is assigned double unitPrice = 0.0; // zero is the initial value double quantity = 0.0; System.out.print("Enter product: "); product = input.nextLine(); System.out.print("Enter unit price: "); unitPrice = input.nextDouble(); System.out.print("Enter quantity: "); quantity = input.nextDouble(); } } Every identifier/variable that we will use on a java program must be declared and initialized. This is good programming practice. product is declared as String because this is a text entry. We used two double quotes to signify that the initial value of product is null. unitPrice and quantity are all declared with double data type with initial value of 0.0. If you have not familiarized with data types and naming conventions used on this book, please go to this link. To compute the total price of the product, we need to multiply unit price and quantity. Therefore, a new variable is needed to hold the result of the product. We use totalPrice as our identifier and declare it with the same data type double since we are computing two double data types. Again, we initialize our unused variables with zero. The next obvious thing to do is to write the formula that will handle the computation after accepting all the entry values. Here, the formula is: totalPrice =quantity * unitPrice; If you have not familiarized on how to code java formulas, go to this link.

31


Make sure you are typing the correct variable name; totalprice is different from totalPrice. Java is case sensitive. You will encounter compiler error if you are using two different names on your program. The best practice is to declare immediately the variable on the top of the program after main() once you decide on the name you will use. Our code at this point will look like this: package javaPackage; import java.util.Scanner; public class NetPrice { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Initialize our variables that will handle our inputs String product = ""; // null value is assigned double unitPrice = 0.0; // zero is the initial value double quantity = 0.0; // Initialize variable we used for computation double totalPrice = 0.0; System.out.print("Enter product: "); product = input.nextLine(); System.out.print("Enter unit price: "); unitPrice = input.nextDouble(); System.out.print("Enter quantity: "); quantity = input.nextDouble(); totalPrice = quantity * unitPrice; } } Our program already achieved computing the values of the possible entries on the program. The next step we do is to compute for the discount and net price. We will use the following codes to compute for the values: discount = totalPrice*0.1; netPrice = totalPrice-discount; Again, to avoid error of undeclared variables, we go at the top of the program where we declare our variables and initialized it with value zero. You can declare and initialize variables on the same line with one double declaration. Just separate the two variables with a comma and terminate it with semicolon at the end.

32


double discount=0.0, netPrice=0.0; As we update our code, we have: package javaPackage; import java.util.Scanner; public class NetPrice { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Initialize our variables that will handle our inputs String product = ""; // null value is assigned double unitPrice = 0.0; // zero is the initial value double quantity = 0.0; // Initialize variable we used for computation double totalPrice = 0.0; double discount = 0.0, netPrice = 0.0; System.out.print("Enter product: "); product = input.nextLine(); System.out.print("Enter unit price: "); unitPrice = input.nextDouble(); System.out.print("Enter quantity: "); quantity = input.nextDouble(); totalPrice = quantity * unitPrice; discount = totalPrice * 0.1; netPrice = totalPrice - discount; } } We reach now where we output the results of these computations. Issue the following System.out.println() statements concatenating our variables with the literal texts required: System.out.println("\nThe product is " + product); System.out.println("Total price is " + totalPrice + " dollars"); System.out.println("Discount is " + discount + " dollars"); System.out.println("\nNet price is " + netPrice + " dollars"); The program looks like this: package javaPackage;

33


import java.util.Scanner; public class NetPrice { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Initialize our variables that will handle our inputs String product = ""; // null value is assigned double unitPrice = 0.0; // zero is the initial value double quantity = 0.0; // Initialize variable we used for computation double totalPrice = 0.0; double discount = 0.0, netPrice = 0.0; System.out.print("Enter product: "); product = input.nextLine(); System.out.print("Enter unit price: "); unitPrice = input.nextDouble(); System.out.print("Enter quantity: "); quantity = input.nextDouble(); totalPrice = quantity * unitPrice; discount = totalPrice * 0.1; netPrice = totalPrice - discount; System.out.println("\nThe product is " + product); System.out.println("Total price is " + totalPrice + " dollars"); System.out.println("Discount is " + discount + " dollars"); System.out.println("\nNet price is " + netPrice + " dollars"); } } Compile and run the program. If we use the same set of inputs on our example we have this result: Enter product: iPhone 4s Enter unit price: 399.97 Enter quantity: 20 The product is iPhone 4s Total price is 7999.400000000001 dollars Discount is 799.94 dollars

34


Net Price is 7199.460000000001 dollars

Format double value with Two Decimal places The question is: How do we achieve the same output just like we have at the sample output as we define our problem on the start? We use the special class program DecimalFormat. This is included on the package java.text.DecimalFormat. We include and declare this package at the location where we declare our Scanner package. Just enter beneath the Scanner package declaration with this statement: import java.text.DecimalFormat; Next, we instantiate or create an object to make use of the DecimalFormat class. On this case, we name our object df. Instantiate the statement after the Scanner class object declaration with this line: DecimalFormat df = new DecimalFormat(“#,###,###.00�); You will notice that there is a string/text #,###,###.00 enclosed within double quotes. This serves as format of what output should be. If your value reached thousands it will include a comma with two decimal places; two commas if it reached millions with two decimal places. DecimalFormat has a method format(). We make use of this method together with the df object we have declared. Thus, our displaying of the results will be revised this way: System.out.println("Total price is " + df.format(totalPrice) + " dollars"); System.out.println("Discount is " + df.format(discount) + " dollars"); System.out.println("\nNet price is " + df.format(netPrice) + " dollars"); Our final code should be like this: package javaPackage; import java.util.Scanner; import java.text.DecimalFormat; public class NetPrice { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("#,###,###.00"); // Initialize our variables that will handle our inputs String product = ""; // null value is assigned

35


double unitPrice = 0.0; // zero is the initial value double quantity = 0.0; // Initialize variable we used for computation double totalPrice = 0.0; double discount = 0.0, netPrice = 0.0; System.out.print("Enter product: "); product = input.nextLine(); System.out.print("Enter unit price: "); unitPrice = input.nextDouble(); System.out.print("Enter quantity: "); quantity = input.nextDouble(); totalPrice = quantity * unitPrice; discount = totalPrice * 0.1; netPrice = totalPrice - discount; System.out.println("\nThe product is " + product); System.out.println("Total price is " + df.format(totalPrice) + " dollars"); System.out.println("Discount is " + df.format(discount) + " dollars"); System.out.println("\nNet price is " + df.format(netPrice) + " dollars"); } } Now, we achieve this result: Enter product: iPhone 4s Enter unit price: 399.97 Enter quantity: 20 The product is iPhone 4s Total price is 7,999.40 dollars Discount is 799.94 dollars Net price is 7,199.46 dollars

EXERCISE 4 I. Express and evaluate the given formula in java. 1. Assume base = 10 and height = 2: Area Triangle = base â—? height

36


2 2. Assume a = 2 and b = 1 c = a2 + 2ab – 4(b+a) 2 3. Assume principal is 1000 and n=3 which is the number of years; i = 5% as interest rate per year: m = principal(1+ i)n 4. Assume x = 1 and y = - 2 z = xy + (x – y ) % 3 + 4 5. Assume a = 2 and b = 10 c = a + b % 4 – (b – a*3) II. Write the equivalent java expression for the following: 1. 2. 3. 4. 5.

n = n /16; unitPrice = 0.5*unitPrice; counter = counter + 1; fee = fee – discount; year = year – 1;

III. Design a program: 1. Write java program Rectangle that computes the perimeter and area of a rectangle based on the input length and width values of the user. Sample Input/Output: Enter length: 12.5 Enter width: 36.55 Perimeter is 98.10 meters Area is 456.87 meters 2. Formulate java program Average that computes the average price of a commodity on 3 succeeding days: Sample Input/Output: Enter item: gasoline Price in day 1: 39.99

37


Price in day 2: 40.02 Price in day 3: 38.97 Average price of gasoline is 39.66 per gallon 3. Design java program Age that computes the age of a person depending on the current year and birth year entered. Use int as data type for all computation. Sample Input/Output: What is your name? Patricia Enter current year: 2014 Enter birth year: 1995 Patricia, your age on 2014 is 19 4. Create java program Tuition that displays the amount he is going to pay if he avails different payment mode. 10% discount is imposed if payment made in cash; 5% penalty for payment made in 2 installments; 10% penalty for payment made in 3 installments. Sample Input/Output: Enter name of student: Jerry Esperanza Enter number of units enrolled: 18 Enter price per unit: 741.00 Jerry Esperanza, you could available the following payment mode: Computed Tuition fee: 13,338.00 dollars Payment Mode: Cash Payment: 12,004.20 dollars 2-installment: 14,004.90 dollars 3-installment: 14,671.8 dollars 5. Create java program Washer computes the area of the washer based on the input side. Use the given figure to formulate the solution to the problem. Hint: Compute the area of the square and deduct it to the area of the circle. Use 3.1416 as a value of pi.

38


Sample Input/Output: Enter s: 10.5 Area of the washer is 40.11 millimeters

Chapter 5: SELECTION STRUCTURE Upon completion of this chapter you should able to:      

Use if statement when setting a condition; Understand how if-else statement works; Set a nested if on multiple conditions;. Combine logical operators on a condition; How to use switch/case statement on multi-value variable; Simulate given program and determine its output.

Programs can select a path what to execute when condition is met. That path can consist of one or multiple commands depending on what it wants to achieve. We are going to discuss java statements that select those paths whenever condition is satisfied.

THE if STATEMENT The statement underneath the if statement is executed when the condition is true code1: if (<condition>) { <statement 1>; .

39


. . <statement n>; } Executing multiple statements requires a beginning and ending curly braces. This signifies the block to be executed when condition is met. Condition must be enclosed with parenthesis. Consider the given code:

num has a value of 143. Next is an if statement, the program validates the condition. Since the relational operator tests the equality of num and value 143, the condition is true: the word “I love you” is printed (line 4). The next statement that will be executed is line 6 that displays “End of program”. How about if the condition is false? Consider the program:

The above program executes assignment of value 7 and 3 to num1 and num2 respectively. Next is an if statement that tests if num1 is less than num2. The condition is false because 7 (num1) is greater than 3 (num2). The if statement simply by-passes the two

40


statements inside the curly braces and proceeds to the next statement and displays “End of program�.

THE if-else STATEMENT The if statement executes only if the condition is set to true. How about if you want to execute statements if condition becomes false? We use the if-else statement on with the given syntax code2: if (<condition>) { <statement 1>; . . . <statement n>; } else { <statement 1>; . . . <statement n>; } Once the condition is not satisfied (false) the program will branch immediately to the statements underneath the else statement. Note that the statements are also enclosed with curly braces to show the block of statements to be executed when condition is set to false. Let us have a good working example. The following program tests if a number is a positive or negative code3. import java.util.Scanner; public class PositiveOrNegative { public static void main(String[] args) { Scanner input= new Scanner(System.in); int number=0; System.out.print("Enter number: "); number= input.nextInt(); if (number > 0) { System.out.println(number+" is a positive number");

41


} else { System.out.println(number+" is a negative number"); } } }

Nested if-else statement Sometimes, we are bound to select path situated on multiple conditions. The previous sample program tells if a number is positive or negative. How about if the number entered is zero? We can modify the program with this form code4: import java.util.Scanner; public class PositiveOrNegative { public static void main(String[] args) { Scanner input= new Scanner(System.in); int number=0; System.out.print("Enter number: "); number= input.nextInt(); if (number > 0) { System.out.println(number+" is a positive number"); } else if (number < 0) { System.out.println(number+" is a negative number"); } else { System.out.println(number+” is origin”); } System.out.println(“The program terminates”); } }

42


Let us say entered number is 7, the if condition implements System.out.println(number+" is a positive number");. After executing this line, it will jump out from the condition and execute the next statement System.out.println(“The program terminates”); If the entered number is -4, the first if condition is invalidated. Next, it will validate the next condition else if (number<0). Because the statement is true, it will execute statement System.out.println(number+" is a negative number"); and jumps out from the block and executes the next statement System.out.println(“The program terminates”); If the first two conditions are not met, it will just execute underneath the else statement System.out.println(number+” is origin”); and proceed to the next line of codes.

Logical Operators In some situation we test our logic with not just one but two or more conditions before we execute a given statement. Let us consider these: 1. If test1score is greater than 90 AND test2score is greater than 90 , make employee manager. 2. If test1score is greater than 90 OR test2score is greater than 90, make employee supervisor 3. If NOT test1score is greater than 90, make employee agent. Logical AND acts as operator between operand conditions “test1score is greater than 90” and “test2score is greater than 90”. Here, both conditions must be true in order to execute “make employee manager”. If one operand is set not true, the entire condition is false. Logical operator OR has the same format but works differently. You only need one operand to be set to true to make the entire condition true. If all operands are false makes the entire condition false. Logical NOT is placed before the operand (same in Java). Here, the employee becomes agent if test1score is less or equal to 90. We use double ampersand (&&) for logical AND operator; double pipe symbol (||) for logical OR and exclamation point (!) for NOT operator. Thus, if we convert the given scenario and combine it with if-else statement we have the following codes code5: import java.util.Scanner; public class EmployeeTest { public static void main(String[] args) {

43


Scanner input= new Scanner(System.in); int test1score=0, test2score=0; System.out.print("Enter test 1 score: "); test1score= input.nextInt(); System.out.print("Enter test 2 score: "); test2score= input.nextInt();

if ((test1score > 90) && (test2score > 90)) { System.out.println("Make employee manager"); } else if ((test1score > 90) || (test2score > 90)) { System.out.println("Make employee supervisor"); } else if (!(test1score>90)) { System.out.println("Make employee agent"); } } } Note that every condition and the ENTIRE compound condition statement must be enclosed with parentheses. Here, we have used also relational operators to test our conditions. See relational operators to review on this link.

THE switch/case STATEMENT On some situation where a value is reached we need to execute a series of statements if the condition is true. As an alternative in handling this kind of scenario is the use of the switch/case statement. The syntax in using this statement is as follows code 5.1: <intVarName>; switch(<intVarName>) { case <first value of intVarName>: <statement 1>; <statement 2>; <statement n>; break; nd case < 2 value of intVarName> : <statement 1>; <statement 2>;

44


<statement n>; break; . . . case < n value of intVarName>

: <statement 1>; <statement 2>; <statement n>; break;

default: <statement 1>; <statement 2>; <statement n>; break; } switch/case statement works only on integer and character data type; the use of it in float, double data type is not allowed. To help us understand fully how it works, let us have a concrete example for this: Design java program AirFare that imposes a discount fare to student and senior citizen on an airline company. Student gets 10% discount; senior citizen gets 20%; ordinary customer gets no discount. Sample Input/Output: Enter fare amount: 100.0 Enter customer code [0=Ordinary, 1=Student, 2=Senior] : 1 Customer is student Discount is 10.0 dollars Net Fare is 90.0 dollars Let us setup the basics first like we did on previous exercises code6: import java.util.Scanner; import java.text.DecimalFormat; public class AirFare { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("###,###.00"); } }

45


We continue by facilitating the inputs of the program code 7: import java.util.Scanner; import java.text.DecimalFormat; public class AirFare { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("###,###.00"); //Declare input variables double fare=0.0; int custCode=0; // Accepts the inputs of the program System.out.print("Enter fare amount: "); fare=input.nextDouble(); System.out.print( "Enter customer code [0=Ordinary, 1=Student, 2=Senior] : "); custCode=input.nextInt(); } } fare is declared as double to handle entry even on cent level. custCode is declared as integer because this would be the integer variable that we will going to test on our switch/case statement. Our next approach is to determine what kind of customer we have on the entry and the discount rate we impose. We need to use a variable customer declared as String to handle the text description of the customer; discRate declared as double for the discount rate. We initialize customer with a null value and discRate with zero. These are the two variables we need to control depending on the customer code inputted on the program code8. import java.util.Scanner; import java.text.DecimalFormat; public class AirFare { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("###,###.00"); //Declare input variables double fare=0.0;

46


int custCode=0; String customer=""; double discRate=0.0; // Accepts the inputs of the program System.out.print("Enter fare amount: "); fare=input.nextDouble(); System.out.print( "Enter customer code [0=Ordinary, 1=Student, 2=Senior] : "); custCode=input.nextInt(); } } Our program displays ordinary, student or senior citizen based on the customer code inputted. It also imposes 0% for ordinary; 10% for student; 20% to senior citizen. Things we need to adjust when we use it inside the switch/case statement. Within our switch/case statement, if the value of custCode is 0, customer is set to “ordinary”; custCode is 1 customer is set to “student”; custCode is 2 customer is set to “senior citizen”. When an entry is not within those 3 number codes, our customer will have a value of “Invalid code”. The discRate is also adjusted. For 0 custCode we have 0.0; 1 has 0.1 and 2 has 0.2 rate. Since our discRate is set to 0.0 as our initial value, we don’t have a problem if an invalid code is entered. It will remain as such when we compute for the discount code9. import java.util.Scanner; import java.text.DecimalFormat; public class AirFare { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("###,###.00"); //Declare input variables double fare=0.0; int custCode=0; String customer=""; double discRate=0.0; // Accepts the inputs of the program System.out.print("Enter fare amount: "); fare=input.nextDouble();

47


System.out.print( "Enter customer code [0=Ordinary, 1=Student, 2=Senior] : "); custCode=input.nextInt(); switch(custCode) { case 0: customer= "ordinary"; discRate=0.0; break; case 1: customer="student"; discRate=0.1; break; case 2: customer="senior citizen"; discRate=0.2; break; default: customer="Invalid code"; } } } Now, we are ready to compute for the discount and the net fare after deducting the discount. We just multiply the discRate with fare to get discount. Then, we deduct from fare the value of the discount. Simultaneously, we declare the discount and netFare on the part where we initialize our variables. Again, we set its initial value to zero and double as its data type code10. import java.util.Scanner; import java.text.DecimalFormat; public class AirFare { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("###,###.00"); //Declare input variables double fare=0.0; int custCode=0; String customer=""; double discRate=0.0; double netFare=0.0, discount=0.0;

48


// Accepts the inputs of the program System.out.print("Enter fare amount: "); fare=input.nextDouble(); System.out.print( "Enter customer code [0=Ordinary, 1=Student, 2=Senior] : "); custCode=input.nextInt(); switch(custCode) { case 0: customer= "ordinary"; discRate=0.0; break; case 1: customer="student"; discRate=0.1; break; case 2: customer="senior citizen"; discRate=0.2; break; default: customer="Invalid code"; } //Compute discount and net fare discount=fare*discRate; netFare=fare-discount; } } On its final form, we display its output. We format all numeric values with two decimal places code 11. import java.util.Scanner; import java.text.DecimalFormat; public class AirFare { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("###,###.00"); //Declare input variables double fare=0.0; int custCode=0; String customer=""; double discRate=0.0;

49


double netFare=0.0, discount=0.0; // Accepts the inputs of the program System.out.print("Enter fare amount: "); fare=input.nextDouble(); System.out.print( "Enter customer code [0=Ordinary, 1=Student, 2=Senior] : "); custCode=input.nextInt(); switch(custCode) { case 0: customer= "ordinary"; discRate=0.0; break; case 1: customer="student"; discRate=0.1; break; case 2: customer="senior citizen"; discRate=0.2; break; default: customer="Invalid code"; } //Compute discount and net fare discount=fare*discRate; netFare=fare-discount; System.out.println("\nCustomer is " + customer); System.out.println("Discount is " + df.format(discount) + " dollars"); System.out.println("\nNet fare is " + df.format(netFare) + " dollars"); } } Our next example deals with the use of character data type on switch statement. Consider the following problem: Design java program Job that will determine if the employee is an agent, team leader or operations manager. Agent code is A; Team Leader is L; Operations manager is M; other codes is invalid. Sample Input/output:

50


Enter employee code: A Employee is agent We do not have a numeric value on this problem. There is no need to use the DecimalFormat package. So, our starter program will look like this code 12. import java.util.Scanner; public class Job { public static void main(String[] args) { Scanner input = new Scanner(System.in); } } All inputs used by Scanner class are considered as String. We declare empCodeStr as the repository for the employee code entered as input. It has a null value as we initialize it at the start of the program code 13. import java.util.Scanner; public class Job { public static void main(String[] args) { Scanner input = new Scanner(System.in); String empCodeStr=""; System.out.print("Enter employee code: "); empCodeStr=input.nextLine(); } } There is a possibility that the input is in lower case letter. To simplify our approach in validating the inputs, we need to convert the input letter into upper case form. We overwrite what ever currently in stored in variable empCodeStr. We do this by this line: empCodeStr=empCodeStr.toUpperCase(); Our updates will look like this code14: import java.util.Scanner; public class Job { public static void main(String[] args) {

51


Scanner input = new Scanner(System.in); String empCodeStr=""; System.out.print("Enter employee code: "); empCodeStr=input.nextLine(); //Convert lower case to upper case letter empCodeStr=empCodeStr.toUpperCase(); } } We need to create a character data type variable empCodeChar that we will use for our switch statement. Here, we declare empCodeChar as character data type with an initial value of anything in stored at empCodeStr. The 0 in empCodeStr.charAt(0) represents the part of the text value of empCodeStr that needs to be extracted. Counting starts at 0 not 1. Code 15: import java.util.Scanner; public class Job { public static void main(String[] args) { Scanner input = new Scanner(System.in); String empCodeStr=""; System.out.print("Enter employee code: "); empCodeStr=input.nextLine(); //Convert lower case to upper case letter empCodeStr=empCodeStr.toUpperCase(); // Declare empCodeChar and // extract first character of empCodeStr // and store it on empCodeChar as its initial value char empCodeChar=empCodeStr.charAt(0); } } We validate now empCodeChar in our switch statement. We assign a String variable employee as the description for the code entered. Let us update our declaration area with this variable with a null as its initial value. If we have ‘A’ entered our employee will have a value of “Agent”; ‘B’ will have employee with a value of “Team Leader” and ‘M’ with “Operations Manager”. If none

52


of these letters is entered we just update it with a value “Invalid� as indicated on the default. Take not that character values are enclosed with single quote (not double quotes). You need to do this when working with character data type. We concatenate employee on its output at the end. See code 16: import java.util.Scanner; public class Job { public static void main(String[] args) { Scanner input = new Scanner(System.in); String empCodeStr="", employee="";

System.out.print("Enter employee code: "); empCodeStr=input.nextLine(); // Convert lower case to upper case letter empCodeStr=empCodeStr.toUpperCase(); // Declare empCodeChar and // extract first character of empCodeStr // and store it on empCodeChar as its initial value char empCodeChar=empCodeStr.charAt(0); switch(empCodeChar) { case 'A': employee="Agent"; break; case 'L': employee="Team Leader"; break; case 'M': employee="Operations Manager"; break; default: employee="Invalid"; } System.out.println("\nEmployee is " + employee); } }

53


SIMULATE: Determine the output One of the important skills of a programmer is able to read other programs; not just his/her own. Ideas abound on how to solve a problem with possibility of multiple approaches to solution. Internet offers lot of solutions but only few knows how to decipher what the program means. This e-book includes a section of SIMULATE: Determine the output that will help programmer decode what other programmers approach in solving the problem. We will read and trace values of variables line by line through our simulation board. Consider the code below (code 17): public class SimulateEx1 { public static void main(String[] args) { int a=1, b=4, c=0; c = b + a*2; b++; a = c*(b-1) + 7%3; System.out.println("Value of a is " + a); System.out.println("Value of b is " + b); System.out.println("Value of c is " + c); if (b>c) { a--; c++; } else { b--; b += 4; c *= 3; } System.out.println(); System.out.println("Values of a, b, c are " + a + ", " + b + ", " + c + " respectively."); } }

54


As we declare integer variable a, b, and c, we assign its initial value with 1, 4, and 0, respectively. We evaluate c = b+ a*2; Applying the rule of precedence, multiply a with 2. The product resulted to a value of 2 which is added to b with a value of 4. The sum of the expression is 6 which is assigned to variable c. Increment b. b has now a value of 5. Again, applying the rule of precedence, we evaluate first the operation inside the parenthesis. Deduct 1 from b (which has a value of 5) before multiplying it with c (with a value of 6). Modulus operation (%) between 7 and 3 achieves 1. The final operation on this line is addition of 24 and 1 that produces a sum of 25 which is assigned to a. The next three lines display the literal text enclosed in double quotes concatenated/joined with the values of a, b, and c. Values display at this point are 25, 5, and 6. The if statement evaluates if b is greater than c. We know that the current of b is 5 and c has a value of 6. Therefore, the evaluation has false result bypassing the statements underneath the if statement. Instead, the block statements underneath the else statement are executed. Decrement value of b. b is now 4. Add 4 to b. b is updated with a value of 8. Multiply 6 (value of c) with 3. This operation produces a new value for c which is 18. After skipping a new line System.out.println();, display the value of a, b and c with the concatenated literal texts “Values of a, b, c are”, couple of commas and the word “ respectively.”. On this line we achieve: Values of a, b, c are 25. 8, 18 respectively.

55


Let us move on with the next simulation exercise (see code 17). Here, we start declaring integer variables a, b, c with values 25, 8, 18 respectively. The succeeding line declares String variable message with null value. valueGreater30 is boolean data type with initial value set to true. Nested if statement is in the works. Determine if the compound conditions inside the first if statement produce true. (a < 30) is true since a is 25; (b>8) is false since b is 8. Because the entire condition is compounded with logical operator AND (&&), this makes the if statement set to false (underneath statements are not implemented). The program evaluates the else if. b is 8 so it makes (b==8) true; c is 18 so it makes (c==12) false. The two evaluations are compounded by logical operator OR (||) makes the whole statement set to true: we implement the block statements within the else if. public class SimulateEx2 { public static void main(String[] args) { int a=25, b=8, c=18; String message=""; boolean valueGreater30=true; if ((a<30) && (b>8))

56


{ c %= 4; b += (a*c); } else if ((b == 8) || (c == 12)) { b %= 3; a--; c += 5; } else { b /= 3; } System.out.println(a + "\t" + b + "\t" + c); b = b + 1; switch(b) { case 0: message="Programming rocks!"; break; case 1: message="Java rules the internet!"; break; case 2: message="Android apps use Java!"; break; default: message="I love simulation!"; } a = c - b; c = b + a; valueGreater30 = c > 30; if (valueGreater30) { message += " C# adapts Java codes"; } System.out.println("\nFinal value of a is " + a); System.out.println("Final value of b is " + b); System.out.println("Final value of c is " + c); System.out.println("\nMessage is " + message); } } b %=3 assigns b with a value of 2. The remainder of 8 divided by 2 (integer division) is 2. The value of b is updated from 8 to 2 because of the assignment operator equal.

57


Decrement a. a has now a value of 24. Add 5 from c makes c 23. This expression is the same as c = c + 5;. The nested if met one condition set to true. The next else statement is skipped together with its block statement underneath it. We display the values of a,b, and c separated by \t tab character. This line displays: 24

2

23

We add 1 to b making it 3. We validate b by the switch statement. On this validation, none of the case conditions is met. Therefore, execute the default statement. Assign “I love simulation” to string variable message. Evaluate a = c – b;. Since c is 23, subtract the value of b (2) makes a with difference of 21. We now update the value of boolean variable valueGreater30. Validate if c > 30;. c is 23, hence, the value assigned to valueGreater30 is false. The block statement within the if condition is skipped because valueGreater30 is false. Display the values of a, b, c, and message concatenated with literal texts. Please note that \n new line characters are also used within the double quotes of the literal texts. We have now this as our final output:

58


EXERCISE 5 I. Simulation: Determine the output: 1. public class SimulateEx3 { public static void main(String[] args) { int x=-1, y=7, c=0; c = y + x * -4; y += c; x -= 3; if (x>0) { x++; } if ((c>=20) || (y > 8)) { y += x; } else { y %= 3; x *= c; c--; } System.out.println("Value of x is " + x); System.out.println("Value of y is " + y); System.out.println("Value of c is " + c); } } 2. public class SimulateEx4 { public static void main(String[] args) { String gradeEquiv=""; double grade=0; double classStanding=90.0, exam=85.0;

59


grade=classStanding*0.6 + exam*0.4; if ((grade<=100) && (grade>=95)) { gradeEquiv="A+"; } else if ((grade<=94) && (grade>=90)) { gradeEquiv="A"; } else if ((grade<=89) && (grade>=85)) { gradeEquiv="B"; } else if ((grade<=84) && (grade>=80)) { gradeEquiv="C"; } else if ((grade<=79) && (grade>=75)) { gradeEquiv="C-"; } else { gradeEquiv="F"; } System.out.println("Computed grade is : " + grade); System.out.println("Equivalent grade is : " + gradeEquiv); } } 3. public class SimulateEx5 { public static void main(String[] args) { int day=4; day++; switch(day) { case 1: System.out.println("Day is Sunday"); break; case 2: System.out.println("Day is Monday");

60


break; case 3: System.out.println("Day is Tuesday"); break; case 4: case 5: case 6: System.out.println("Day can be Wednesday" + ", Thursday or Friday"); break; case 7: System.out.println("Day is Saturday"); break; default: System.out.println("Day is undefine"); } } } 4. public class SimulateEx6 { public static void main(String[] args) { String status="Temperature is "; int temp=104; temp = (temp - 32)* 5/9; temp -= 5; status += temp + ". "; switch(temp) { case 40: case 39: case 38: case 37: status +="extremely hot!"; break; case 36: case 35: case 34: case 33: status +="A hot day!"; break; case 32: case 31: case 30: case 29: case 28: status += "Fair."; break; case 27:

61


case 26: case 25: case 24: status += "A cool day!"; break; default: status += "Undetermined..."; } System.out.println(status); } } II. Program Exercise 1. Design program AgeGroup that will determine if age belongs to underage, young adult, adult, senior. Under age is 1-17; young adult is from 18-30; adult is from 31-59; senior is from 60 or more. Display “Invalid age” for negative numbers. Sample Input/Output: Enter age: 24 Young adult 2. Formulate program SalesDiscount for a particular sales range generated by sale. Follow the given discount range: Price range 0 - 10,000 10,001 - 20,000 20,001 - 50,000 50,001 - 100,000 Greater than 100,000

Discount 0% 5% 10% 15% 20%

Sample Input/Output: Enter product: modem router Enter price : 14500.50 Price of modem router is 14,500.50 Discount is 725.02 Net Price is 13,775.48 3. Create program AverageGrade that will compute for the average of the student and determine on three subjects and determine if falls under the following category: Average Grade 100 - 95 94 - 89 88 – 83 82 - 78

Grade Status President lister Dean lister Average Student Fair

62


lower 78

Failure

more than 100

Invalid grade

Note: Do not use logical OR or AND on your solution. Sample Input/Output: Enter name: John Doe Enter grade in Physics: 96 Enter grade in Algebra: 93.50 Enter grade in Programming: 98 John Doe average grade is 95.83 President lister 4. Create program Fare that computes discount of passenger. Use the given table: fareCode O S C

Passenger Ordinary Student Senior Citizen

Discount 0% 5% 10%

if traveling in Business class additional 1000.0 additional 700.0 additional 500.0

If code is not within the selection make all output zero. Use switch case on your solution. Sample input/output: Enter fare: 8000.0 Passenger type [O,S,C]: C Travelling in business class [Y/N]: Y Discount: 800.00 Business class charge: 500.00 New fare: 7,700.00

63


Chapter 6: CONTROL STRUCTURES Upon completion of this chapter, the student will be able to:    

Understand how looping statement shorten codes on repetitive tasks; Use do-while, while and for loop statements Simulate program with looping statement Construct program with looping statement within another looping statement

There are some cases where we need to execute the same set of codes all over again to meet the requirement of the program. Retyping same statements makes our program cumbersome and longer. Long programs are not easy to maintain and slows down the reader in understanding it. Consider the following requirement: Design program ILoveYou that displays “I love you!” message 3 times. Normally, the approach of a beginner who is just learning to program is to execute 3 System.out.println(“I love you!”); to meet the requirement. Thus, we have: public class ILoveYou { public static void main(String[] args) { System.out.println("I love you!"); System.out.println("I love you!"); System.out.println("I love you!"); } } The requirement of the program changes over time and the requirement have changed to display the message 50 times. Are we going to code 50 times of System.out.println() to meet the requirement? That is not an efficient approach. We will now employ the use of the three looping statement to address the issue on three different approaches.

The while statement while loop statement pretest a boolean expression before executing the statement/s under its block. Boolean expression is also the condition placed inside the parenthesis after the while statement. If the condition is true, the statement/s underneath within the block is/are executed. Then it will loop back on the condition and test again. If the condition is false, the while statement terminates, exits from the block and executes the next statement.

64


To control the number of times the while loop executes, we need to place a variable or a counter to test the condition/boolean expression of the statement. We have now a syntax: <variable initial value>; while (condition) { statement/s; . . increment / decrement <variable>; } Let us modify and apply the while statement on our ILoveYou program: public class ILoveYou { public static void main(String[] args) { int ctr = 0; while (ctr < 3) { System.out.println("I love you!"); ctr++; } } } Let us study how the looping occurs within the program:

65


Our variable/identifier ctr will store an initial value of zero. The next step is to evaluate the condition associated with the while statement. The question is: is ctr less than 3? Since we just assigned value 0 to ctr, 0 is less than 3. If the condition is true, the program executes the block statements WITHIN the braces. This time the program execute System.out.println (“I love you!”) displaying the message. ctr increments by 1. As the figure suggests, reaching the closing brace of the while statement force the program to loop back and evaluate the while (condition) again. Is ctr less than 3? Our ctr has a value 1. As the condition becomes true again (1 is less than 3), it will display “I love you!” for second time. Increment againt ctr (making ctr = 2). Loop back (again after reaching the closing brace). Is ctr less than 3? True. ctr is 2. That makes it less than 3. Execute the System.out.prinln(“I love you!”); for the third time. Add 1 again to ctr. ctr now is 3. Closing brace again is reached. Loop back to the while (ctr < 3) statement. Is ctr less than 3? Since our ctr has a value of 3, that makes the condition false. The false result exits the while statement block and executes the next statement OUTSIDE it. There is no instruction after the while statement. The program terminates. How about the 50 “I love you!”s? Well, you just change 3 with 50 inside the while condition and you’re up and running. So, is it possible to make it 10,000 or a million? Yes, of course! See the video tutorial version

The do – while statement There are other looping statements you could use beside the while statement and still produce the same result. The do – while statement is different from while statement because boolean expression is validated after executing the block statement within the do – while statement (post test):

As we use a variable that would set the limit of the number of times it will execute, we have: <variable initial value>; do { statement/s; .

66


. increment / decrement <variable>; } while (condition);

NOTE: You need to terminate the while (condition) with a semicolon. Let us now implement on the same problem with the do-while approach. This time we will use a decrement operation and change the condition with less than equal: public class DoWhileILoveYou { public static void main(String[] args) { int ctr; ctr = 3; do { System.out.println("I love you!"); ctr--; } while (ctr >= 1); } } Isolating the do – while operation itself, we have:

ctr has an initial value of 3. The program proceeds immediately in implementing the block statement within the do - while loop. “I love you!” is printed; ctr is decremented. ctr now has a value of 2. Evaluate the boolean expression inside the while condition. Is ctr > = 1? ctr is 2 and it is greater than 1. That sets the condition to true. Loop back and implement the block statements again. Print “I love you!” for the second time; decrement 1 from ctr. ctr is now 1.

67


Is ctr >= 1? True because ctr is equal to 1. Loop back again. Display “I love you!” for the third time; deduct 1 again from ctr; ctr has a value 0. Is ctr >= 1? ctr is equal to 0. Therefore, the condition is set to false. The program exits on the do-while block statement. No more instructions after the do-while statement, the program terminates. See the video tutorial version

The for statement The last looping statement you could choose from is the for loop. It has the following syntax:

We have the equivalent code for the ILoveYou program with the following: public class ForILoveYou { public static void main (String[] args) { int ctr; for (ctr=0; ctr < 3; ctr++) { System.out.println("I love you!"); } } } Let us isolate the codes that implements the looping. Step 1: As the figure suggests, the first statement evaluated on a for statement is the assignment of initial value of the variable/identifier. ctr is set to 0. Step 2: Is ctr less than 3? True. Step 3: The program prints “I love you!”.

68


Step 4: After reaching the closing brace of the block, the program loops back and executes increment ctr. ctr has now a value of 1. Step 5: Is ctr less than 3? True. Print again “I love you!” for the second time. Loop again and increment ctr with 1. ctr is now 2. Is ctr less than 3? Still true. Print “I love you!” for the third time. Loop back. Add 1 to ctr. ctr is now set to 3. Is ctr less than 3. False. ctr is equal to 3: not less than. The program escapes the for loop block.

At first, the for loop statement seems complicated but it is mostly used by experts and intermediate programmers. For them it is handy to use compared to other looping statements. But still, the choice is yours. As long as you understand which one is more applicable to make the program easier to maintain afterwards. See the video tutorial version Working Example: Design program SquareCube that displays the square and cube of an integer from 1 to n. Sample Input/Output Enter n: 3 Integer Square Cube 1 2 3

1 4 9

1 8 27

As we did before, we name first our program class with SquareCube. We include the Scanner class to be used in the input of n.

69


Let us declare our input object for the Scanner class; integer n for the number we will input. Prompt message “Enter n: “ and convert the input number into an integer and assign the value to n. Print the header text before we generate the squares and cubes of our number series. On this case we need a counter that will increment as we proceed in generating the values. Declare ctr on the declaration area. Since our generation of values starts with 1, initialize ctr with 1. Use while as our looping statement to do the computing and generating of values. Our condition will be a comparison of ctr versus n. We need to check if ctr has already reached the limit n in generating the squares and cubes of the numbers. To compute for the square of the number, we multiply ctr with ctr. To compute for the cube, we multiply ctr with ctr with ctr or simply the square of ctr with another ctr. We name our accumulators with the same name: square and cube. Declare it on top of our declaration area with initial value set to zero and data type int. We are now ready to print the values of the square and cube on an integer. Display the value ctr. Separate ctr value with a \t tab character for the square value. Do the same thing for the cube value. The generation of values does not end with 1 alone. On our sample input we need to generate n with the value of 3. So our limit was set actually with 3. Increment ctr with ctr++. ctr now has a value of 2. That will set the whole block of our while statement. As the loop ends with the closing brace, it will evaluate again at the beginning of our while statement if ctr is less than or equal to n. Is ctr <= n? Is 2 <= 3? True. Implement again the block statements inside while. square will have a new value 4 (2 multiply by 2). cube will have a value 8 ( 4 multiplied by 2). Print again the new set of values with 2 as the value of ctr; 4 for the square; 8 for the cube. Increment ctr. ctr is now 3. Loop back. Is 3 <= 3? True. 3 multiply by 3 is 9. That would be the value of square. 9 multiply by 3 is 27. That would be the value of cube. Print 3, 9 and 27.

70


Increment ctr. ctr is now 4. Test if ctr is less than or equal to n which is 3. 4 <= 3? False. The execution proceeds outside the while loop. Since there is no more thing to do next, the program terminates. Below is the code for our program: package javaPackage import java.util.Scanner; public class SquareCube { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n, ctr = 1; int square = 0, cube = 0; System.out.print("Enter n: "); n=input.nextInt(); System.out.println("\nInteger\tSquare\tCube\n"); while (ctr <= n) { square = ctr * ctr; cube = square * ctr; System.out.println(ctr + "\t" + square + "\t" + cube); ctr++; } } } Let us move on with our next example: Design program SumOdd that will display the odd numbers from last number to 1. Display its sum at the end. Sample Input/Output: Enter last number: 15 15 13 11 9 7 5 3 1 Sum is 64 Name our program SumOdd. Call our Scanner class for the input. Declare input as our object for the Scanner class and lastNum for the inputted last number as int with initial value of 0. Write the prompt input message. Assign the inputted number to lastNum.

71


This time we will use a for loop statement to generate the odd values. We will assign the value of the lastNum to our counter ctrNum. Test ctrNum if it greater than or equal to 1. Decrement ctrNum. Do not forget to declare ctrNum at the declaration area. Initialize it with 0. To separate our output to the input area, we type System.out.println() to move to the next line. Inside the block of the looping statement, we need to test if the number is odd or even. We could do this if a number is divisible by 2 by lastNum modulus of 2. If the operation equals to 1, then, the number is odd. We could do this by using a boolean variable named oddNum. We test it by statement: oddNum = ctrNum % 2 ==1. Don’t forget to declare the boolean variable oddNum at the declaration area with initial value of false. We are testing ctrNum if it is an odd number because only odd numbers should be displayed and accumulated to compute the sum. With an if statement, we could check now if oddNum is true or false. If true, we display the number and accumulate the sum. If false, we just proceed with the next execution of the loop. Declare sum at the declaration area. Print ctrNum with a space concatenated with it to separate it for the next number to be printed out. Accumulate sum by adding the ctrNum to it. Reaching the end brace of the loop, it will loop back and decrement ctrNum. Test again the condition until it reaches 0. If it has not reach 0 yet, it will again implement the statements within for loop. As the for loop terminates, we need to print the sum of its number. The \n is needed to move the cursor to the next line. Refer below as the final code of our program: package javaPackage; import java.util.Scanner; public class SumOdd { public static void main(String[] args) { Scanner input = new Scanner(System.in); int lastNum = 0; int ctrNum = 0, sum = 0; boolean oddNum = false;

72


System.out.print("Enter last number: "); lastNum = input.nextInt(); System.out.println(); for (ctrNum=lastNum; ctrNum >= 1; ctrNum--) { oddNum = ctrNum % 2 == 1; if (oddNum) { System.out.print(ctrNum + " "); sum += ctrNum; } } System.out.println("\nSum is " + sum); } } See the video tutorial version

Indefinite Loop How do you compute the average of numbers when you don’t know the divisor for the sum of the numbers? On this situation, you let the user enters all the numbers until he/she decides to finish inputting. Consider this: Design program AverageNumber that computes the average number of all the entries entered by the user. User enters -1 to end data entry and proceed displaying the average. Sample Input/Output: Enter number [-1 to quit]: 1.5 Enter number [-1 to quit]: 3.5 Enter number [-1 to quit]: 5.0 Enter number [-1 to quit]: 6.8 Enter number [-1 to quit]: -1 Average number is 4.2 We start importing and declaring the Scanner class for our input object. Anticipate that the numbers to be entered are with decimal point. We use number as our variable name in holding all the entries. Initialize it with value 0. This would be the beginning of our program: import java.util.Scanner; public class AverageNumber { public static void main(String[] args) {

73


Scanner input = new Scanner(System.in); double number = 0; } } Let us use the while statement that will handle the indefinite entry of numbers. To create that illussion of no definite end, we set the boolean expression inside the while statement parentheses to true. Inside the while body we place our prompt message together with the variable number that will accept the numbers entered. Take note that we use nextDouble() method is used for numbers with decimal numbers. We have our program at this point: package javaPackage; import java.util.Scanner; public class AverageNumber { public static void main(String[] args) { Scanner input = new Scanner(System.in); double number=0; while (true) { System.out.print("Enter number [-1 to quit]: "); number = input.nextDouble(); } } } The logic of the program is accumulate/add all the numbers that are not -1. Here we need a variable that will do that. We use sum that will hold and add the values entered. Create also variable divisor that will count all valid inputs. We insert next on the input the if condition that will validate if number is not equal to -1. Inside the if condition, accumulate number assign to sum and increment our divisor. Do not forget to declare our variables in the declaration area. package javaPackage; import java.util.Scanner; public class AverageNumber { public static void main(String[] args) { Scanner input = new Scanner(System.in); double number = 0, sum = 0, divisor = 0; while (true)

74


{ System.out.print("Enter number [-1 to quit]: "); number = input.nextDouble(); if (number != -1) { sum += number; divisor++; } } } } What will happen if number is -1? Good question. We will set our else condition with a statement break. Break here means is to escape the while loop. After that, outside the while loop, we print our average for the numbers. We simply concatenate text “\nAverage number is “ with the sum/divisor. Refer below as our final program: package javaPackage; import java.util.Scanner; public class AverageNumber { public static void main(String[] args) { Scanner input = new Scanner(System.in); double number = 0, sum = 0, divisor = 0; while (true) { System.out.print("Enter number [-1 to quit]: "); number = input.nextDouble(); if (number != -1) { sum += number; divisor++; } else { break; } } System.out.println("\nAverage number is " + sum/divisor); } }

75


Loop within a loop Is it possible to have a looping statement within another looping statement? Of course. Sometimes, this simplifies the code solution of a problem. Consider the following: Design program SquareHash that displays the number of hashes in square figure depending on the size entered by the user. Sample Input/Output: Enter size of hash: 3 ### ### ### How do we formulate a solution for this kind of problem? Let us observe few things: 1. The hash symbol prints with number of times on each row depending on the value the user entered. On our example, if we entered 3 we generate 3 hashes on each row. 2. The number of rows to be printed depends also on the size entered by the user. So, it is the same with the number of hashes printed on each row. It is a 3 by 3 figure.

What would be the algorithm of the solution for this? 1. Accept the number size of the hash entered. 2. Set the starting value of rows to print. 3. Continue printing on each row as long as it is less than or equal to the number of size of the hash entered. 3.1 Set the starting value of number of hash to print. 3.2 Continue printing the hash symbol as long as number of hash to print is less than or equal to the number of size of the hash entered. 3.2.1 Print hash symbol horizontally.

76


3.2.2 Increment the value of number of hash already printed. 3.3 Advance line to the next row. 3.4 Increment the value of row already printed. You could refer to the flow chart below if you prefer to present the logic this way:

We are done presenting the flow of the program. Let us code this in java. Name our program SquareHash. Include the Scanner class to facilitate the input entered by user. Display the input prompt that will the the user to enter the size. Assign the value of the entered on the prompt to variable hashSize. Do not forget to declare hashSize as int on the declaration area. Set to 0 to as its initial value. package javaPackage; import java.util.Scanner; public class SquareHash {

77


public static void main(String[] args) { Scanner input = new Scanner(System.in); int hashSize = 0; System.out.print("Enter size of the hash: "); hashSize = input.nextInt(); } } Follow the logic of the pseudo code or flow chart. Declare all the variables on the declaration as you assign new variables in the program. Our solution consist two looping statements. The outer loop uses the while statement; inner loop (loop within the loop) uses for.

We use the statement System.out.print() to print the hash symbol horizontally. System.out.println() to advance on the next line since the cursor stays on the same line because of the System.out.print() command. Adding 1 to numHash happens when the for statement loops back. Incrementing 1 to row happens before we loop back to the while statement. Refer to the final code for the problem: package javaPackage; import java.util.Scanner; public class SquareHash { public static void main(String[] args) { Scanner input = new Scanner(System.in); int hashSize = 0; int row, numHash;

78


System.out.print("Enter size of the hash: "); hashSize = input.nextInt(); row = 1; while (row <= hashSize) { for (numHash = 1; numHash <= hashSize; numHash++) { System.out.print("#"); } System.out.println(); row++; } } }

Compile and test the program by entering different hash size values. Simulate: Determine the output Let us learn to read other programs created by other programmers. Refer to the code below: package javaPackage; public class SimulateEx7 { public static void main (String[] args) { int x, y, z=1; do { x = 3; while (x >= 1) { for (y = 1; y <= x; y++) { System.out.print(x + " "); // one space is } // printed after x System.out.println(); x--; } System.out.println(); z++; } while (z < 3); }

79


} It would be helpful if we place looping scope boundaries/arrows to set where our looping statement starts and where it ends. Refer to the figure below:

First, we declare variable x, y, and z. z has initial value set to 1. Looping Section 1 starts here. The program proceeds entering at do – while loop. Looping Section 2 starts here. Immediately, the loop executes assigning 3 to variable x. Another looping statement is encountered. This time it is the while loop. The while statement validates a boolean expression. Is x >= 1? The value of x at this point is 3. 3 is greater than 1. The boolean expression is true. The program implements the block statements within the while statement. Looping Section 3 starts here. Within the while block there is another looping statement: the for loop. The for loop assigns an initial value of 1 to variable y. Validate the condition if y < = x.

80


Is y <= x? y is 1 and x is 3. Therefore, the condition is true. Implement the System.out.print (x + “ “). Print the current value of x (which is 3) and a space after it. As the for loops back, increment value of y. y now is 2. Is y <= x? y is 2 and x is 3. True again. Print again the value of x (which is 3) with a space after it. Increment y as for loops back again. This time, y is now 3. Is 3 <= 3 (as the condition validates again)? True. Print again the value of x (3) with a space after it. We have our first row output below: 3 3 3 Increment y as for loops back. y now is 4. Is y <= x? 4 <= 3? False. The program escapes from the for loop. The cursor now proceeds on the next line with the System.out.println() statement. Decrement the value of x. x now is 2. Loop back on the while statement and validate again the boolean expression x >= 1. Is x >= 1? x is 2 so the condition is set to true. Enter again the within the while block statements. Assign 1 to y. Validate the expression y <= x. Is y <= x? 1 <= 2? The answer is true. Print the value of x (which is 2) concatenated with a space. Loop within the for statement. Increment y. y is now 2. Is 2 <= 2? True. Print the value of x (still 2) with a space after it. Loop again the for statement. Increment y. This time y is 3. Is y = x? 3 <= 2? False. Exit the for loop block. Output at this point is: 3 3 3 2 2 Cursor advance with the next line by statement System.out.println(). Decrement x. x is 1. Loop back on while statement. Is x >= 1? x is 1 therefore, equal to 1. True. Assign 1 once again to y as you enter the for loop statement. Is y <= x? True again since y and x has a value of 1 each. Print value x joined by a space. Loop for statement. Increment y. y is 2.

81


Is 2 <= 1? False. Escape once again the for loop statement. Output now is: 3 3 3 2 2 1 Looping section 3 ends here. Advance cursor one line by System.out.println(). Decrement x. x has value 0. Loop back on while statement. Is x >= 1? False. 0 is not greater than or equal to 1. Exit on the while loop. Looping section 2 ends here. Cursor advance another line as another System.out.println() is implemented. Increment z. z is now 2. Validate the do – while condition. Is z < 3? Is 2 < 3? True. Implement again where the section 1 starts and up to Looping section 2 ends here. Its déjà vu once more. Advance another line with System.out.println(). Add 1 to z. z now is 3. Is z < 3? Is 3 < 3? False. They are equal. Exit on do – while loop. Looping section 1 ends here. There is no more statement to do after the do – while loop. Program terminates. The final output of the program is: 333 22 1 333 22 1 See the video tutorial version

EXERCISE 6 I. Program Simulation Simulate: Determine the output

82


1. package javaPackage; import java.text.DecimalFormat; public class SimulateEx8 { public static void main(String[] args) { DecimalFormat df = new DecimalFormat("##,###.00"); int year = 0; double $my_investment = 1000.0, interest = 0.0, $money = 0.0; // Printing of the Headers System.out.print("Year\t"); System.out.print("Amount\t\t"); System.out.print("Interest\t"); System.out.print("Year-end Money"); // Place the cursor to the nextline System.out.println(); // Loop details for (year = 1; year <= 5; year++) { interest = $my_investment * 0.1; $money = $my_investment + interest; // Printing of Details System.out.print(year + "\t"); System.out.print(df.format($my_investment) + "\t"); System.out.print(df.format(interest) + "\t\t" + df.format($money)); // Cursor to proceed on the nextline System.out.println(); $my_investment=$money; //Set current money } // to investment } } 2. package javaPackage; public class SimulateEx9 { public static void main(String[] args) {

83


int a, c; for(a = 5; a >= 1; a -= 1) { if (a < 5) { c = 4; while (c >= a) { // Print one space System.out.print(" "); c = c - 1; } } System.out.println("&"); } } } 3. package javaPackage; public class SimulateEx10 { public static void main(String[] args) { int theNumber = 23100, factor = 1; System.out.print("Factors of "+ theNumber + " are "); do { if (factor != 1) { if (theNumber % factor == 0) { theNumber = theNumber / factor; System.out.print(factor + " "); } if ((theNumber % factor) != 0) { factor++; } if (factor > theNumber) { factor = 0; } }

84


else { factor++; } } while (factor != 0); } } 4. package javaPackage; public class SimulateEx11 { public static void main (String args[]) { int x, y, z; for (x = 11; x >= 1; x -= 1) { if ((x % 2) != 0) { y = 11; while(y > x) { System.out.print (" "); // one space is y -= 2; // inside the double quotes } z=1; do { System.out.print("@"); z++; } while (z <= x); System.out.println(); } } } } 5. package javaPackage; public class SimulateEx12 { public static void main(String[] args) { int a = 1, b, c = 0;

85


while (a <= 5) { for (b = 1; b <= 5; b++) { c = a * b; System.out.print(c + "\t"); } System.out.println(); a++; } } } 6. package javaPackage; public class SimulateEx13 { public static void main(String[] args) { int num = 4; int row, col; int magic = 0, deductor = 0, adder = 1; for (row = 1; row <= num; row++) { for (col = 1; col <= num; col++) { if (col == 1) { magic = row; } else if ((col % 2) == 0) { magic = num*col - deductor; } else { magic += adder; } System.out.print(magic + "\t"); } System.out.println(); deductor++; adder += 2; }

86


} } II. Programming Exercise 1. Using for loop statement , create program EvenSquareCube that produces the program below. Maximum of 3 System.out.println() or System.out.print() should be used in the solution. Sample Output: Number 2 4 6 8 10

Square 4 16 36 64 100

Cube 8 64 216 512 1000

Total

220

1800

2. Design program DollarTriangle that allows user to enter the base size of dollar figure using any of the looping statements. Maximum of 3 System.out.print() or System.out.println() should be seen on the program. Use two looping statements only. Hint: There are spaces to be printed(except on the last line) before the the dollar sign. Sample Input/Output: Enter base size of dollar triangle: 5 $ $$ $$$ $$$$ $$$$$ 3. Formulate program RowColNumber that generates the series of numbers below using any of the combination of looping statements. Maximum of 2 System.out.println() or System.out.print() should be used in the solution. Use only two looping statements only. 25 24 23 22 21

20 19 18 17 16

15 14 13 12 11

10 9 8 7 6

5 4 3 2 1

4. Design a program Fibonacci where user inputs an integer value and the program generates the Fibonacci series from 1 to the input value.

87


Sample Input and Output: Enter integer: 21 Prime Numbers are 1 1 2 3 5 8 13 21 5. Create program Matrix that display the matrix of a number entered by user. If user enters 4, it will generate 16 numbers; if 3, it will generate 9 numbers. Arrange the series of numbers in the order just like the sample output. Maximum 3 System.out.println() or System.out.print() should be used in the solution. Use two looping statements only. Sample Input/Output: Enter matrix to generate (n by n): 4 16 9 8 1

15 10 7 2

14 11 6 3

13 12 5 4

6. Allow program Temperature convert farenheit to celsius or vice versa. After computing the conversion values, the program returns to Main Menu. Use the following formula for the conversion: fahrenheit = 9.0 / 5.0 * celsius + 32.0; celsius = (fahrenheit – 32.0) * 5.0 / 9.0; Sample Input/Output: Main Menu a. Celsius to Fahrenheit b. Farenheit to Celsius c. Exit Choose option [a, b, or c]: A Celsius – Fahrenheit Conversion Enter celsius: 5.0 Farenheit equivalent is 41.0 Main Menu a. Celsius to Fahrenheit b. Farenheit to Celsius c. Exit Choose option [a, b, or c]: B

88


Fahrenheit - Celsius Conversion Enter fahrenheit: 41.0 Celsius equivalent is 5.0 Main Menu a. Celsius to Fahrenheit b. Farenheit to Celsius c. Exit Choose option [a, b, or c]: C End of program. Good bye!

89


Chapter 7: Methods At the end of this chapter, the student will be able to:     

Apply the divide-and-conquer approach using method; Specify each element on method declaration; Assign method name that signifies action; Distinguish the data type difference of return values of methods; Simulate the return values of methods.

Method is nothing new to us. On previous chapters, we are working on one method called main(). main() is the nerve center of a working java program. This is where the java interpreter seeks the first set of instructions to execute. Method is simply a sub-program that is called by main() (which is also a method) or other programs. The idea behind of breaking big program into small sub-programs is to maintain or isolate other programs that go haywire during run time. It is a divide-conquer approach. Let us think like a doctor performing a kidney operation. Because the urinary system is faulty, he isolates the kidney in checking if it is properly working. Have you heard a doctor performing a kidney operation by opening up the brain? Though in rare cases, you may need to do that, it is not a good idea to include the brain in the whole operation. Same with designing a program; it is not advisable that you dump all the codes inside the main(). As you develop a more complex program, the codes become longer and cumbersome to read. When one calculation or operation is not working properly on a 10,000 lines of code, do you need to start reading from the start up to the point where the program gives error results? You could do that but it is not a good approach. Our first example Let us say, we design program Border that prints a border line before and after the message “Java rocks!”. So, our sample output would be: ========== Java rocks! ========== As can see, the border is printed twice. Does it mean we need to code printing of border twice? Will that make our program efficient or longer? With the method approach, you need to code once and just call the method once again if you need to print another set of borders. Let us see the following program:

90


public class Border { public static void main(String[] args) { printBorder(); System.out.println("Java rocks!"); printBorder(); } public static void printBorder() { int x; for ( x = 1; x <=10; x++) { System.out.print("="); } System.out.println(); } } As the java interpreter implements the program Border starting from main(), the program calls first method printBorder() and prints 10 equal signs symbol horizontally. The printBorder() statement on main() instructs the program to jump out from main() and look for a method printBorder(). Upon reaching that method, it will execute the lines inside its body and return to the calling program (on this case it is main()). When the program returns to its calling main() method, it prints the text “Java rocks!�. It calls once again the printBorder() and do exactly the same tasks in printing the border line. Then, the program terminates.

Anatomy of a Method Declaration 1. Access modifier. The class (or program) may allow other classes to use the method you have just defined. Other declarations you could use other than public are private, protected and package. Discussion of the use of private, protected and package is beyond the discussion of this book. We use these modifiers on Object Oriented Programming (OOP). For now, we will just use public modifier on all methods that we will create. 2. Method type. There are two types of methods in a java program: instance method and class method. What we have used since the start of the book is a class method. You identify the class method with the word static. Failure to include static would mean that the method you are declaring is an instance method. Again, instance method is an OOP concept that is beyond the discussion of this book. Never mind if the concept is not clear to you yet. All method type declarations we will use for this book will be static. 3. Return data type. Think all methods that we will define are just like a variable we are declaring at the start of the program. In declaring a variable in a program we need to define its data type. Same goes with method. It can be declared as int, double, float,

91


char, boolean or as another class String. When you say return data type, the method needs to return a value depending on the declaration you have just defined. String declaration means return a text value to the calling method/program; double and float mean return a number with fractional value; int returns whole number; boolean returns value either true or false. When void is used on method declaration, the method needs not to return anything to the calling method/program. All other data types (except for void) defined on method declaration must use a return statement within the body of the method.

4. Method name. The programmer has a liberty to name a method of one’s choice. Though, good programming practice insists that method name should connote action. This means that the first word to be used is an action word: verb. Example of these are: printBorder, calculateSalary, displayOutput, isValid, etc. 5. Parameters. If you need to pass information to a method, you need to define the list of parameters or arguments within the parenthesis. Each parameter must define its data type separated by a comma if there is more than one parameter. You don’t need to define a parameter if there is no need to pass information to the method. We will have good example for these. 6. Method body. Just like our main() method you define the scope of the method by a set of curly braces. Inside the body is where statements are located that execute the functionality of the method.

Coffee Vendo Machine: An Example To fully grasp the concept of methods, let us mimic the operation of a coffee vendo machine. From the figure, consider the different parts as methods that are assigned to handle particular task.

92


The vendo machine accepts 2-dollar bill or coin combinations. The price of coffee is 1.50 dollars. Only 1 type of coffee is dispensed by the machine. If money is enough, dispense coffee; hence, notify with message “Money not enough”. Issue change if money is more than its price.

For the sake of discussion, dispenseCoffee() and issueChange() will display message “Coffee is served”, “Your change is ____ dollar”, respectively instead of the actual coffee and coin change (of course!). acceptMoney() handles the bill and coin slot. notify() will display message on its small screen “Money not enough” is payment is short from coffee price. There are mechanisms that are inside (not visible) the vendo machine. We will consider main() as the central control which handles the overall operation of the machine; isMoneyEnough() as a sensor which determines if payment is enough. We will start our program naming it CoffeeVendo. The control operation will be located on main(). Declare money as double data type to handle coins and 2-dollar bill denomination. Initialize it first with 0. To make the machine operational, we need to insert money to dispense the coffee. The method (mechanism) that accepts money is acceptMoney(). Call the method from main() and assign its value whatever the money detected by the acceptMoney() method. acceptMoney() must execute tasks to detect the amount inserted on the machine. So, we need to declare/define the structure of acceptMoney() method. The method MUST return a value to the calling method. On this case, the monetary value acceptMoney() returns must be aligned to the repository data type of variable money which catches the value

93


detected on acceptMoney() method. This is why the data type of acceptMoney() is also declared as double. There is no information passed by the main() to acceptMoney() method. Therefore, there is no need to include parameters inside the parenthesis of the method. Proceed now in defining the body of the method and what statement it should contain to get the value of the money inserted. Here we insert define the Scanner class that will handle the input of the pay amount. We also declare another variable payAmount that is effective only within the scope of the method. Likewise, payAmount should also be declared with double data type. Mimic the vendo machine ready to accept money through its coin and/or bill slot with the prompt “Enter money: “. Assign value to variable payAmount when user inserted/(typed) on these two slots. This value would be numeric amount to be passed back to the calling method main(). We do this by the return payAmount; statement. So far, this would be the code status of our program: import java.util.Scanner; public class CoffeeVendo { public static void main(String[] args) { double money = 0.0; money = acceptMoney(); } public static double acceptMoney() { Scanner input = new Scanner(System.in); double payAmount = 0.0; System.out.print("Enter money : "); payAmount = input.nextDouble(); return payAmount; } } After calling the acceptMoney(), money variable, at this point, has already a value passed by the method. We are now ready to evaluate money. We test money by creating a method isMoneyEnough(). You may ask: why do you need to create another method if this can easily done by a simple if statement? Good point. The idea here is to have a good example of a method that returns a boolean value with an information passed on it.

94


Inside the parenthesis of isMoneyEnough() we include the variable money as the information passed by main() as you call isMoneyEnough() into action. If isMoneyEnough() returns a true value, it will call dispenseCoffee(); hence, it will call notify() with the text “Money not enough�. Let us define now the structure of the isMoneyEnough() method. Write first the corresponding public static access modifier and method type that we usually do in declaring a method. The if statement on main() is expecting a boolean expression inside its parenthesis, therefore, set isMoneyEnough() with a boolean return data type also. isMoneyEnough is the name of our method. What is the difference between variable money used in main() and myMoney as declared in the structure of isMoneyEnough() as parameter? money is the value being passed by main() to the method isMoneyEnough(). myMoney on the other hand is the catcher of the value money variable has. Think money as the actual bill or coins we drop/insert on the vendo slot. myMoney is the container that catches the bill or coins. So you may say that money and myMoney is actually equal to each other. Whatever the value of money is also the value of myMoney. The money being passed has a data type double, myMoney, catching it should have the same. myMoney is the replica of money. However, anything we do on myMoney (because it is isolated within isMoneyEnough()) will not affect the value of money. Let us say we reduce myMoney inside isMoneyEnough(), money will retain its original value at main(). We are trying to evaluate the money being passed on isMoneyEnough(). myMoney as the replica, would be in effect must be tested inside the body of the method. If myMoney is greater than or equal to 1.50 the method returns true else false. Having now a boolean value for isMoneyEnough(), the evaluation now of the if statement will determine if it calls dispenseCoffee() or notify(). This would be the progress of our codes as we include isMoneyEnough() method: import java.util.Scanner; public class CoffeeVendo { public static void main(String[] args) { double money = 0.0; money = acceptMoney(); if (isMoneyEnough(money)) { dispenseCoffee(); } else {

95


notify("Money not enough"); } } public static double acceptMoney() { Scanner input = new Scanner(System.in); double payAmount = 0.0; System.out.print("Enter money : "); payAmount = input.nextDouble(); return payAmount; } public static boolean isMoneyEnough(double myMoney) { if (myMoney >= 1.50) { return true; } else { return false; } } } Our requirement dictates that dispenseCoffee() displays “Coffee is served” when called; nothing more. This is why on the definition/declaration of dispenseCoffee() it needs not to return anything from the calling program with the word void on its return data type. No information is passed on the method so the parameter list is empty. The body of the method simply has the statement System.out.println(“Coffee is served”);. Once done on its execution, it will return to the calling program (which is main() on this example). Take note that we did not use the return statement here because the data type of dispenseCoffee() is void. notify() method is almost has the same functionality of dispenseCoffee(). The difference is notify() has a text being passed on its method. That text must have a container or a variable to catch it. On this case, we have message with String data type declaration. We test at the end if the money inserted/entered is more than 1.50 dollars; issue change if it is. Concatenate the whatever value generated by issueChange() with text “\nYour change is “ and “ dollar”. As we define issueChange() on our declaration, we find double is declared on its return data type. Why? There are instances that it will return a fractional value such as 0.25,

96


0.50. issueChange() also include a parameter named payment declared as double. Again, payment here is the replica of money used in calling issueChange() on main(). change is created to hold the result of the change on payment. Simply deduct 1.5 from payment to achieve change. As change is returned, issueChange() has the value of change. This would be the value concatenated on the text of System.out.println(). This would be our final codes for CoffeeVendo: import java.util.Scanner; public class CoffeeVendo { public static void main(String[] args) { double money = 0.0; money = acceptMoney(); if (isMoneyEnough(money)) { dispenseCoffee(); } else { notify("Money not enough"); } if (money > 1.50) { System.out.println("\nYour change is :"+ issueChange(money)+ " dollar"); } } public static double acceptMoney() { Scanner input = new Scanner(System.in); double payAmount = 0.0; System.out.print("Enter money : "); payAmount = input.nextDouble(); return payAmount; } public static boolean isMoneyEnough(double myMoney) { if (myMoney >= 1.50) {

97


return true; } else { return false; } } public static void dispenseCoffee() { System.out.println("Coffee is served"); } public static void notify(String message) { System.out.println(message); } public static double issueChange(double payment) { double change= 0.0; change = payment - 1.50; return change; } }

More on Methods Passed-by-Value When we pass information from one method to another, we call this pass-by-value. The CoffeeVendo example used pass-by-value in isMoneyEnough() and issueChange() methods. Money is passed which is essential in achieving the methods task. Consider the given problem: Create a method-oriented program Cylinder that computes the lateral surface area and volume of the cylinder. Designate methods computeLateralArea() and computeVolume() that will facilitate the computation of its values. No System.out.println() should be seen on these methods. Use the following formulas in solving the requirements: lateralAreaCylinder = 2 * 3.1416 *radius * (radius + height); volumeCylinder = 3.1416 * radius * radius * height; diameter = 2 * radius;

98


Sample Input/Output: Enter diameter: 2.5 Enter height: 3.0 Lateral surface of the cylinder is 33.3795 Volume of the cylinder is 14.72625 To start up, create program Cylinder declaring its Scanner class with its input object and variables diameter and height as double data type. Initialize diameter and height with 0.0 value. Include the input prompts that will get the diameter and height of the cylinder. We are ready to display the surface lateral area and volume of the figure. Concatenate the corresponding texts to methods computeLateralArea() and computeVolume() to display the results by System.out.println() statement. Our program should look like this: import java.util.Scanner; public class Cylinder { public static void main(String[] args) { Scanner input = new Scanner(System.in); double diameter = 0.0, height = 0.0; System.out.print("Enter diameter: "); diameter = input.nextDouble(); System.out.print("Enter height: "); height = input.nextDouble();

99


System.out.println("\nLateral surface of the cylinder is " + computeLateralArea(diameter, height)); System.out.println("Volume of the cylinder is " + computeVolume(diameter/2.0, height)); } } Let us define now the structure of the two methods. computeLateralArea() must return fractional value that is why the return data type is double. Its parameters include d and h (declared double separately) that will absorb the values passed by diameter and height respectively. As we proceed on the body of the method, declare variable radius since our formula for computing the lateral area need this. Initialize radius with value 0.0. In assigning a value for radius, get the half value of diameter. All data are in place to compute for the lateral area. Declare/initialize variable lateralAreaCylinder that will hold the computed values of the surface area. Assign the value for the variable with the formula guide above. Return the value with a return statement. computeVolume() will have the same structure just like the computeLateralArea(). Though we prefer to change the parameter names of the values passed, it will have the same double data type declaration. You will notice here that variable r stands for radius; h2 for height. On the values passed in main() for the method computeVolume(), diameter is already being divided with 2. It is the same formula in obtaining the radius; therefore, the value passed is already divided in a half. No more variables used in the body of the method. This is a good approach in making your program sleek by directly returning the value whatever will be the result of the mathematical operation. We have the following codes as the working program: import java.util.Scanner; public class Cylinder { public static void main(String[] args) { Scanner input = new Scanner(System.in); double diameter = 0.0, height = 0.0; System.out.print("Enter diameter: "); diameter = input.nextDouble(); System.out.print("Enter height: "); height = input.nextDouble(); System.out.println("\nLateral surface of the cylinder is "

100


+ computeLateralArea(diameter, height)); System.out.println("Volume of the cylinder is " + computeVolume(diameter/2.0, height)); } public static double computeLateralArea(double d, double h) { double radius = 0.0; double lateralAreaCylinder = 0.0; radius = d / 2.0; lateralAreaCylinder = 2 * 3.1416 * radius * (radius + h); return lateralAreaCylinder; } public static double computeVolume(double r, double h2) { return 3.1416 * r * r * h2; } }

Simulate: Determine the output Let us show the solution of simulation for the program below: public class CD { public static void main(String[] args) { double diameter = 120.0; double radius = 0.0; String output = ""; radius = diameter/2.0; output += "Circumference is "; output += solveCircumference(radius); output += " mm"; output += "\nSurface area of CD is "; output += solveAreaCD(solveAreaCircle(radius), solveAreaCircle((diameter*0.125)/2.0)); output += " sqr mm"; System.out.println(output); }

101


public static double solveCircumference(double rad) { return 2.0 * 3.1416 * rad; } public static double solveAreaCircle(double r) { return 3.1416 * r * r; } public static double solveAreaCD(double outer, double inner) { return outer - inner; } } Initialize diameter, radius and output with 120.0, 0.0, and a null value, respectively. radius is set with a value of 60.0 when diameter is divided by 2.0. Concatenate “Circumference is “ with the current value of output (which is empty ). The value to join with output must come from solveCircumference(). Jump to method solveCircumference() with the parameter value of radius. rad absorb the value of radius. As the return statement do the mathematical operation, it will return a value of 376.992 for solveCircumference() and concatenate again to variable output. “ mm” and “Surface area of CD is “ are added to output variable. Take note that a “\n” newline character is also included moving the text to a new line. solveAreaCD() contains two double data type parameters. On this case, before we could obtain the values of these parameters, we need to jump on method solveAreaCircle() twice to generate it. Take note that each method has different values on its parameters. First the value radius 60.0 is passed to the method achieving 11309.76. The second round of execution of the method passed a radius of 7.5 achieving a value of 176.715. outer variable absorbs 11309.76; inner gets 176.715. Performing subtraction of the two values returns 11133.045 for solveAreaCD(). Again, the value of solveAreaCD() is concatenated with variable output. The last text added to output is “ sqr mm”. Display output with System.out.println() statement. Below is the sample of solution on our simulation board.

102


103


EXERCISE 7 I. Program Simulation Simulate: Determine the output 1. public class SimulateEx14 { public static void main (String[] args) { printBorder(); createTable(); printBorder(); } public static void printBorder() { System.out.print("= = = = = = = = = = = = = = = = = = \n"); } public static void createTable() { int x, y; x = 1; while(true) { for(y = 1; y <= 5; y++) { System.out.print((x * y) +"\t"); } System.out.println(); x++; if (x == 6) { break; } } } } 2.

104


public class SimulateEx15 { public static void main(String[] args) { int numero = 10, number = 3; System.out.println("Result is " + computeNumber(computeNumber(number,numero),4)); } public static int computeNumber (int n, int m) { return n % m; } } 3. public class SimulateEx16 { public static void main (String[] args) { System.out.println(printFigure()); } public static String printFigure() { String figure = ""; int r, c, j, add; r = 1; add = 1; while (r <= 5) { if (r != 1) { for(j = 1; j < r; j++) { figure += (" "); // one blank space } } for(c = 9; c >= add; c--) { figure += "@"; } figure += "\n"; add = add + 2;

105


r++; } return figure; } } 4. public class SimulateEx17 { public static void main(String[] args) { System.out.println(printHeader()); System.out.println("The F of n is : " + evaluateF(5)); System.out.println(deduct()); } public static String printHeader() { String header = ""; header += "Method call test\n"; header+="with parameter values"; return header; } public static int evaluateF(int n) { int f = 1; while(n >= 1) { f *= n; n--; } return f; } public static String deduct() { String info = "The difference of M and N is : "; int m = 8, n = 0; n=evaluateF(4); info += (m-n); return info; } }

106


II. Programming Exercise 1. Create method-oriented program RectangleMethod that computes the perimeter and area of a rectangle. Designate methods calculatePerimeter() and calculateArea() that will facilitate the computation of values. No System.out.println() or display of output should be seen on these methods. Sample Input/Method Enter length: 4.5 Enter width: 2.0 Perimeter is 13.00 meters Area is 9.00 meters 2. Design a method-oriented program Fibonacci that generates a Fibonacci series numbers of n (as input). In Fibonacci, the current third number is the sum of the two previous numbers. Output of the result should be displayed only on main(). Sample Input/Output: Enter number: 15 1 1 2 3 5 8 13 3. Formulate method-oriented program Dozen that computes the number of dozen from the input number of eggs. Assign method determineDozen() that will compute the number of dozen; method showLessDozen() that compute eggs less than 12 eggs. No display of output should be seen on these methods. Sample Input/Output: Enter the number of eggs: 14 Number of dozen: 1 Eggs less than a dozen : 2 4. Write a method isMultiple() on Multiple program that determines for a pair of integers whether the second integer is a multiple of the first. The method should take two integer arguments and return true if the second is a multiple of the first and false otherwise. Sample Input/Output: {Scenario 1} Enter first integer: 2 Enter 2nd integer: 16

107


16 is multiple of 2 --------------------------------------------------Sample Input/Output: {Scenario 2} Enter first integer: 2 Enter 2nd integer: 15 15 is not multiple of 2 5. Dec2Binary is a method-oriented program that converts decimal number system into binary number system. Designate method convert2Binary() that will handle the conversion algorithm. Work only on whole numbers. No System.out.println() should be seen on this method. HINT: Use the technique of successive division of a number. Get the remainder of each successive arithmetic division. Put the result on a string variable and reverse the content. Create method reverseText() that will reverse the content of the string. Use length() and substring() methods of String to get the size and position of text in the string. Example: String test = “hello”; int size = test.length() // size is 5 String extractedText = test.substring(0,1); // starting position 0 and ending // with position 1 is “h” assigned to extractedText Sample Input/Output: Enter the number: 17 Binary equivalent is 10001 6. Modify problem 5. Include conversion of decimal number to octal and hexadecimal number system. Designate additional convert2Octal() and convert2Hexa() methods to do the computation and conversion. No System.out.println() should be present on these methods. Name the program NumberSystem. Sample Input/Output: Enter number: 3054 Hexadecimal equivalent is BEE Octal equivalent is 5756

108


Binary equivalent is 101111101110 7. Create program TriangleMethod that produces a dollar triangle figure with the base entered by the user. If the number entered is 12, the base of the figure will have 12 “$�s. Method generateFigure() will accumulate the formation of the triangle. No System.out.println() or System.out.print() should be seen on this method. Sample Input/Output: Enter base of figure: 12 $ $$ $$$ $$$$ $$$$$ $$$$$$ $$$$$$$ $$$$$$$$ $$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$$ $$$$$$$$$$$$ 8. Write program TriangleNumber that generates triangle with numbers on it. The number entered is the length of the base. No System.out.print() or System.out.println() should be seen on formFigure() method. Sample Input/Output: Enter base length: 9 999999999 88888888 7777777 666666 55555 4444 333 22 1

109


Chapter 8: ARRAYS At the end of this chapter, the student will be able to:    

Work on the concepts of array; Declare array variable in two ways; Simulate the operation of an array with its index and elements; Trace the values of the array elements on two dimensional arrays.

Think array as contiguous memory block with the same data type that can be addressed using its index number. How do we visualize an array? Good question. Imagine we have a wooden cabinet where we store various things. This cabinet is composed of layers where we place, for example, shirts, under wears, wardrobe, etc.

As we convert this into a java program that we have discussed so far, we declare four String variables to identify the content of each cabinet layer: String cabinet1, cabinet2, cabinet3, cabinet4; cabinet1 = “socks”; cabinet2 = “underwear”; cabinet3 = “shirts”; cabinet4 = “dresser”; Instead of declaring 4 different variables (cabinet1, cabinet2…), we use just one identifier/variable: cabinet. The index number of each signifies the distinction of its element/content. String[] cabinet = new String[4];

110


cabinet[0] = “socks”; cabinet[1] = “underwear”; cabinet[2] = “shirts”; cabinet[3] =”dresser”;

Declare an Array variable We use square bracket [] on the data type to tell the compiler that we are allocating an array identifier/variable. We instantiate it with a new operator declaring the data type with its array size.

Thus, String[] cabinet = new String[4]; declares cabinet is an array variable with String data type and a size of 4. The number of an array index starts with 0 not 1. So, if the last index number of an array is 10, the array size is 11. Identify first array size before using it. On our example, we place 4 at the right side of our declaration after the String data type enclosed in square bracket. We could also declare our array with this form: String cabinet[] = new String[4]; This book will use the first option in declaring arrays.

Assign Value on Array Element To access each element of an array, we use a square bracket after the name variable with its index number. The statements cabinet[0] = “socks”; cabinet[1] = “underwear”; assign value as an element of an array corresponding to its index number. You could use also the following statement as an alternative in declaring and assigning immediately the content of each element:

111


The above statement declares an array cabinet with String data type. Here, we do not need to use the new operator and declare its size. The compiler will detect automatically that the array size is 4 since we have four entries during the declaration and assignment. This is the equivalent of the five statements we have used earlier. Take note of the curly braces used and terminated still with semicolon at the end. The first value of the array you have entered (socks) occupies the first element cabinet[0] and the rest in succeeding manner. Each assignment of value is separated by comma.

Array: A working Example Let us have a working java program that uses an array. Consider the problem: Create an array-oriented program ArrayCabinet that mimics the content of a cabinet on its separate compartments. Socks, underwear, shirts, dresser are assigned separately on each level of the cabinet. Display the content of the cabinet. Here is the first solution to the problem: public class ArrayCabinet { public static void main(String[] args) { String[] cabinet = new String[4]; cabinet[0] = "socks"; cabinet[1] = "underwear"; cabinet[2] = "shirts"; cabinet[3] = "dresser"; System.out.println("The contents of the cabinet are: "); int i = 0; while (i < cabinet.length) { System.out.println(cabinet[i]); i++; } } } The output of the program is: The contents of the cabinet are: socks underwear shirts dresser

112


The first five lines within the main() is the declaration and assignment of values of the array cabinet. The succeeding lines display the value of each element of the array. We use while looping statement which validates if we have reached the limit of the array size. cabinet.length generates a value of 4 which is the equivalent array size. We initialize our integer counter i with 0 since our array index starts with 0. i increments after printing the value of cabinet with its current index number. The loop terminates after i reaches a value of 4. The last index number of the array is 3 (not 4). We should note that accessing array beyond its maximum index number (on this case is 3) will produce an array index out of bound error as the compiler compiles the program. As explained previously, we could have another version of the program that produces the same result: public class ArrayCabinetV2 { public static void main(String[] args) { String[] cabinet = {"socks", "underwear", "shirts", "dresser"}; System.out.println("The contents of the cabinet are: "); int i = 0; while (i < cabinet.length) { System.out.println(cabinet[i]); i++; } } }

Arrays with Numeric Data Types Array is not limited to String. We may use array also on double, float, integer and boolean. These array variables may undergo arithmetic operation before accumulating its intended value. Let us consider the given problem: Design program Salary that computes of a number of employees by entering their names, hours worked and rate per hour. A summary report will display the names, hours worked, rate per hour and its computed salary. Display the employees data in reverse order of entry (last name entry should be displayed first) Sample Input/Output: Enter number of employees to process: 3 Enter Employee name: Anne Enter number of hours worked: 80 Enter rate per hour: 12.50

113


Enter Employee name: Karen Enter number of hours worked: 40 Enter rate per hour: 9.0 Enter Employee name: Ivy Enter number of hours worked: 60 Enter rate per hour: 10.50 Salary Report ----------------Name Rate per hour

Hours worked

Salary

Ivy Karen Anne

60.0 40.0 80.0

$630.00 $360.00 $1,000.00

$10.50 $9.00 $12.50

Let us establish first the algorithm for the program. a. The program should be able to handle number of employees depending on the value entry by the user. The number will be our basis for the array size. b. To store rate per hour and hours worked of each employee, assign array variable to hold each value. c. Salary is computed by rate per hour multiplied by hours worked. d. The last entry will be displayed first as the salary report is generated. We start by creating Salary program with the import of Scanner and DecimalFormat classes that we use on inputs and formatting the values output. Declare variable that will hold the number of employees; arrays name, rate, hoursWorked are declared but no size yet identified. Prompt the user to enter the value and assign to numEmp variable. import java.util.Scanner; import java.text.DecimalFormat; public class Salary { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("$#,###.00"); int numEmp = 0; String[] name; double[] rate; double[] hoursWorked;

114


System.out.print("Enter number of employees to process: "); numEmp = input.nextInt(); } } Considering that a value is already assigned to numEmp, we can now declare the size of arrays name, rate, and hoursWorked. Designate a counter (indexNum) that will increment in assigning the value of element of the array variables. Initialize it with value 0. Use while loop statement in handling the entries. This loop terminates only if indexNum is already equal with numEmp. As we update our program, this will look like this: import java.util.Scanner; import java.text.DecimalFormat; public class Salary { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("$#,###.00"); int numEmp = 0; String[] name; double[] rate; double[] hoursWorked; System.out.print("Enter number of employees to process: "); numEmp = input.nextInt(); name = new String[numEmp]; rate = new double[numEmp]; hoursWorked = new double[numEmp]; int indexNum = 0; while (indexNum < numEmp) { System.out.print("\nEnter Employee name: "); name[indexNum] = input.next(); System.out.print("Enter number of hours worked: "); hoursWorked[indexNum] = input.nextDouble(); System.out.print("Enter rate per hour: "); rate[indexNum] = input.nextDouble(); indexNum++;

115


} } } As we begin to print the output of the program, let us print first the headers/title of the output. The use of \t and \n are used within text to properly align the display information. We use another looping statement here: the for statement. Declare integer variable i that will serve as the counter in accessing the element of the arrays. Instead of 0 as the initial value of our counter, use the value of numEmp minus 1. Why did we deduct 1? Since accessing the array starts from the last element, index number is array size minus 1. In order to reach 0 as the first element of an array, we guarantee on our condition (i > = 0) that it needs to reach 0. Variable i is used to extract the values of each element of the arrays. As i decrements the new set of values are generated and printed. Take note that df.format() method of DecimalFormat class is used on rate and on the product of rate and hoursWorked to display the output with dollar currency, comma separated, and two digit decimal point number. A set of \t is also used to align the output to the header title. This would be the final code of the solution: import java.util.Scanner; import java.text.DecimalFormat; public class Salary { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("$#,###.00"); int numEmp = 0; String[] name; double[] rate; double[] hoursWorked; System.out.print("Enter number of employees to process: "); numEmp = input.nextInt(); name = new String[numEmp]; rate = new double[numEmp]; hoursWorked = new double[numEmp]; int indexNum = 0; while (indexNum < numEmp) { System.out.print("\nEnter Employee name: "); name[indexNum] = input.next();

116


System.out.print("Enter number of hours worked: "); hoursWorked[indexNum] = input.nextDouble(); System.out.print("Enter rate per hour: "); rate[indexNum] = input.nextDouble(); indexNum++; } // Printing of Headers System.out.println("\nSalary Report"); System.out.println("-------------"); System.out.println("Name\tRate per hour\tHours Worked\tSalary\n"); for(int i = (numEmp - 1); i >= 0; i--) { System.out.print(name[i] + "\t"); System.out.print(df.format(rate[i]) + "\t\t"); System.out.print(hoursWorked[i] + "\t\t"); System.out.println(df.format(hoursWorked[i] * rate[i])); } } }

Multi-Dimensional Array What we have discussed so far is an example of one-dimensional array. Does it mean array can have two, three or more dimensions? The answer is yes. For simplicity and clarity of the concepts this book will cover only up to two-dimensional array. How do you think in multi dimensional? Think of it as an array within an array. It is an array that is cut into pieces on which each piece has its own compartments or subdivisions. As we based on Cabinet II figure, it is not simply just identifying the row of the cabinet because each row is still sub divided into many compartments on which we identified as columns. When we say, cabinet2[0,0], we are addressing the first row of cabinet2 on the location of column 0. Thus, a two dimensional array is a division with sub divisions.

117


Multi-dimensional Declaration and Assignment of Values Another dimension is added from typical one dimensional array. Let us simplify our discussion for cabinet2. Consider cabinet2 is a 3 by 2 cabinet (3 layers with 2 compartments on each layer). Refer to the figure below.

We can declare and allocate values of the array in two ways. The first is in this format: String[][] cabinet2 = new String[3][2]; cabinet2[0][0] = "gadgets"; cabinet2[0][1] = "pliers"; cabinet2[1][0] = "documents";

118


cabinet2[1][1] = "CDs"; cabinet2[2][0] = "manuals"; cabinet2[2][1] = "candies"; Just as we did on one dimensional array, identify the size of the array. Our cabinet this time has a capacity of 3 by 2. On the declaration we have used the new operator and an additional pair of square brackets on String data type to signify that an additional dimension is used. On the right side of the declaration after the equal sign we assign the size of the two-dimensional array. Assign now the String values of each cell in the array. Please note that the counting for each cell (whatever the dimension is) still starts at 0. Cell reference is addressed by two numeric values. Thus, we say, gadgets are located at cabinet2[0][0] matrix. Another way of declaring and assigning of values that produces the same effect is with this statement: String[][] cabinet2 = {{"gadgets", "pliers"}, {"documents", "CDs"}, {"manuals", "candies"}}; The first layer of the array is enclosed with a pair of curly braces. We separate layers from each one by using a comma. Here, we did not use the index numbers to assign a value for each cell. It is understood that the first set of values indicated and enclosed with curly braces occupies layer 0. The succeeding sets occupy the next index number in progression. How do we display the output of two-dimensional array? Below is the working code for cabinet2. We will name our program same as Cabinet2. public class Cabinet2 { public static void main(String[] args) { String[][] cabinet2 = {{"gadgets", "pliers"}, {"documents", "CDs"}, {"manuals", "candies"}}; int layer, sub; for(layer = 0; layer < cabinet2.length; layer++) { for(sub = 0; sub < cabinet2[layer].length; sub++) { System.out.println("Layer " + layer + " and " + "sub " + sub + " has " + cabinet2[layer][sub]); } System.out.println();

119


} } } Employ the use of inner loop to access cell/element of each array. We declare the counter variables layer and sub. The outer loop condition compares layer from the size of the array cabinet2. cabinet2.length is 3 and will remain as such throughout the program. The inner join condition of the for loop tests if sub is less than cabinet2[layer].length. layer values will vary from 0, 1, 2 but the partition/sub-division within each layer will remain the same. So, cabinet2[layer].length gets the divisions within each row of array which is 2 all through out. There is a separator blank line after changing to another row of the array. The output will look like this: Layer 0 and sub 0 has gadgets Layer 0 and sub 1 has pliers Layer 1 and sub 0 has documents Layer 1 and sub 1 has CDs Layer 2 and sub 0 has manuals Layer 2 and sub 1 has candies

Working Example of Two-dimensional Array Consider the given problem below as we apply the solution of two-dimensional array approach: Create program GradeReport that accepts n number of students with names and grades in three subjects: Physics, Algebra, Programming. Display the entered names, grades and computed average on its summary. The report should display output in reverse order of entry (last name entry should be displayed first). Sample Input/Output: Enter student name: Alex Enter grade in Physics: 93 Enter grade in Algebra: 91 Enter grade in Programming: 88 Enter student name: Eduardo Enter grade in Physics: 85 Enter grade in Algebra: 95 Enter grade in Programming: 89 Enter student name: Dax Enter grade in Physics: 95 Enter grade in Algebra: 96 Enter grade in Programming: 98

120


Enter student name: Allene Enter grade in Physics: 87 Enter grade in Algebra: 88 Enter grade in Programming: 91 Grade Report -----------Student name: Alex Grade in Physics is 93.0 Grade in Algebra is 91.0 Grade in Programming is 88.0 Average grade is: 90.66666666666667 Student name: Eduardo Grade in Physics is 85.0 Grade in Algebra is 95.0 Grade in Programming is 89.0 Average grade is: 89.66666666666667 Student name: Dax Grade in Physics is 95.0 Grade in Algebra is 96.0 Grade in Programming is 98.0 Average grade is: 96.33333333333333 Student name: Allene Grade in Physics is 87.0 Grade in Algebra is 88.0 Grade in Programming is 91.0 Average grade is: 88.66666666666667 Let us establish first the algorithm for the program. a. The program should be able to handle number of students depending on the number entry. The number will be our basis for the array size. b. The three subjects can be placed on an array String. c. The name of the students will be stored on a one-dimensional array. d. Grade is a representation matrix (two-dimensional) between student and a subject. e. Accumulate the total grade per student. Total grade is also a one-dimensional array. f. Display the student name, grade per subject and average grade before generating the next student data.

121


Import the Scanner class utility and name the program GradeReport. Declare input as variable object of Scanner class. Initialize to 0 the integer variable numStud that will be the number figure of how many students to be processed. Declare subject as a one-dimensional array that will hold the 3 subjects Physics, Algebra, and Programming. Prompt the user to enter a value and assign that value to numStud variable. We have this on our initial codes: import java.util.Scanner; public class GradeReport { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numStud = 0; String[] subject = {"Physics", "Algebra", "Programming"}; System.out.print("Enter the number of students to process: "); numStud = input.nextInt(); } } As we proceed to our algorithm c,d, and e, declare studName as one-dimensional String that will hold the name of the students. The array size depends on value entered by user on the prompt message. Make grade two-dimensional as a basis of intersection of student and the corresponding subject assigned to a particular array index keys matrix. Here, array size depends on the numStud value and array size within the array will be set to 3 because we have three subjects involved. totalGrade will hold the accumulated grade value of each student. This is also declared as one-dimensional with double data type. Its size also depends on number of student that will be processed. As an update for our program, we have: import java.util.Scanner; public class GradeReport { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numStud = 0; String[] subject = {"Physics", "Algebra", "Programming"}; System.out.print("Enter the number of students to process: "); numStud = input.nextInt();

122


String[] studName = new String[numStud]; double[][] grade = new double[numStud][3]; double[] totalGrade = new double[numStud]; } } We are now ready to code the data entry part of our program. Our data entry routine will consists of two looping statements: one outer and one inner loop. The inner loop facilitates the assignment of grade values for the three subjects. totalGrade accumulates as we assign the value grade on a particular matrix combination. totalGrade initial value is 0. All numeric data types declared as an array has an initial value of 0. The outer loop holds the each value of the studName array. Again, the basis of the outer loop to go on is the number value entered by user. It should be less than numStud since counting of array starts on 0. gRow would be the counter if we have reached the array ultimate size. gCol counts subject already facilitated versus 3. Why 3 in our inner looping condition? We have three subjects to process. Why gCol < 3 is set on the condition? The array counting of index number starts on 0 not 1. gRow and gCol will set as a pair of coordinates that will track for the value of our twodimensional variable grade. This is the progress of our codes: import java.util.Scanner; public class GradeReport { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numStud = 0; String[] subject = {"Physics", "Algebra", "Programming"}; System.out.print("Enter the number of students to process: "); numStud = input.nextInt(); String[] studName = new String[numStud]; double[][] grade = new double[numStud][3]; double[] totalGrade = new double[numStud]; // Data Entry for (int gRow = 0; gRow < numStud; gRow++) { System.out.print("\nEnter student name: ");

123


studName[gRow] = input.next(); for (int gCol = 0; gCol < 3; gCol++) { System.out.print("Enter grade in " + subject[gCol] + ": "); grade[gRow][gCol] = input.nextDouble(); totalGrade[gRow] += grade[gRow][gCol]; } } } } Same approach will be used on displaying our report as we did on our data entry process. First, we display the header text “Grade Report” and its border line. We will have two looping statements. The outer loop displays the name and average grade of the student. Average grade is actually computed first before it is displayed. We divide totalGrade by 3.0 because of three subjects and we are dealing with double data type value. dispRow and dispCol serve almost same purpose just as gRow and gCol on data entry but this time on displaying the output. We don’t need to identify each subject text since we already assign it on an array subject though identification will be in sequence. The final code will look like this: import java.util.Scanner; public class GradeReport { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numStud = 0; String[] subject = {"Physics", "Algebra", "Programming"}; System.out.print("Enter the number of students to process: "); numStud = input.nextInt(); String[] studName = new String[numStud]; double[][] grade = new double[numStud][3]; double[] totalGrade = new double[numStud]; // Data Entry for (int gRow = 0; gRow < numStud; gRow++) { System.out.print("\nEnter student name: ");

124


studName[gRow] = input.next(); for (int gCol = 0; gCol < 3; gCol++) { System.out.print("Enter grade in " + subject[gCol] + ": "); grade[gRow][gCol] = input.nextDouble(); totalGrade[gRow] += grade[gRow][gCol]; } } // Display Report System.out.println("\nGrade Report"); System.out.println("------------"); for (int dispRow = 0; dispRow < numStud; dispRow++) { System.out.println("\nStudent name: " + studName[dispRow]); for (int dispCol = 0; dispCol < 3; dispCol++ ) { System.out.println(" Grade in " + subject[dispCol] + " is " + grade[dispRow][dispCol]); } System.out.println("Average grade is: " + totalGrade[dispRow]/3.0); } } } NOTE: To avoid error on data entry, enter one-word name only without spaces. Another version of this program will be explained on how to handle more than one-word name.

Simulate: Determine the output In order to practice on what we have learned so far on arrays, let us work on a few simulation exercises. Consider the given program: public class SimulateEx18 { public static void main(String[] args) { int[] number = {1,4,9,16,9,7,4,9,11}; int i, altSum = 0; for (i = 0; i < number.length; i++) {

125


if((i + 1) % 2 == 1) { altSum += number[i]; } else { altSum -= number[i]; } } System.out.print("Sum is " + altSum); } } Declare integer number array with its assigned value as indicated within the braces. Set 0 to variable altSum and declare i as well. Work on for loop statement. Initial value of i is 0. i is compared to number.length which has a value of 9. Array size is 9 since we have nine elements inside array number. Is i less than 9? Yes. 0 is less than 9. Proceed on the next statement inside for loop. Inside the if statement condition, we evaluate first (i+1). The value of add operation is 1 because i at this point is 0. Now, what is now 1 % 2? The answer is 1 since 1 divided 2 is 0 (this is integer division) with a remainder of 1. Is 1 equal equal to 1? The answer is true. Perform the operation beneath the if statement. Add the value of the element number[i] to altSum. The value of i at this point is still 0. So, the value of number[0] is 1. 1 is added at altSum. Loop back and implement increment i in i++. The value of i now is 1. Is 1 less than 9? Evaluate the condition once more. The answer is true. What is (i+1) this time? The answer is 2. 2 % 2 is 0. Therefore, it is not equal to 1. Execute the else statement. altSum value is being subtracted by the value of number[i]. number[1] at this point is 4. Deduct 4 from altSum. altSum now is -3. Increment i again as for statement loops again. The logic of the program is to add value to altSum when i is an odd number; subtract from altSum when i is even. The value to be added or subtracted depends on the value of the element of the array index on the point of execution. Below is the sample solution on our simulation board:

126


SimulateEx19 is a good example for two-dimensional array: public class SimulateEx19 { public static void main(String[] args) { int[][] x = new int[5][5]; int z, row, column; z = 1; while(z <= 25) { for(row = 5;row >= 1; row--) { if (row % 2 == 0) { for(column = 4; column >= 0; column--) { x[row-1][column] = z; z++; } } else { for(column = 0; column <= 4; column++)

127


{ x[row-1][column] = z; z++; } } } } for(row = 0;row < 5;row++) { for(column = 0;column < 5;column++) { System.out.print(x[row][column] + "\t"); } System.out.println(); } } } Declare x as two-dimensional array integer variable. Its array size would be 5 and array partition within the array would also be 5. On our simulation board, let us label array indexes on its division and partition within the division. Counting starts on 0. Integer variable z, row, and column are declared in the program. Assign 1 as initial value of z. Test the condition on the while loop. z is less than 25 because the current value of z is 1. Proceed to the block underneath while statement. Another looping statement is encountered: the for loop. Assign 5 to variable row and test the condition of the loop. Is row greater than or equal to 1? Yes. Proceed executing the block statements within for loop. An if statement is encountered testing if row % 2 is equal to 0. Current value of row is 5; therefore, 5 % 2 is 1, making the condition false. Execute the block statements under else. Another looping statement is met under else statement. Assign 0 to variable column. Proceed on the looping condition. Is column less than or equal to 4? Yes. Assign the value of z to x [row-1][column]. row - 1 is 5 less 1 which is 4; column is 0; z is 1. Therefore, assign value 1 to x[4][0] array location. Increment z making it 2. Loop back and add 1 to column. The condition is set to true again since 1 is still less than 4. Assign now the current value of z to the current array index combination of x. Repeat the process until column becomes 5. At the end of for loop, the value of we have for z is set to 6.

128


Loop on the first for statement. Decrement the value of row. row at this point is already 4. 4 is still greater than 1. Evaluate once again the if statement condition. True. Modules of 4 over 2 is 0. Execute the for loop inside the if statement.

column is set to 4. column >= 0 is true. Execute the statements underneath. Assign the value of z (which is 6) to x[3][4]. Increment z. Loop. Decrement the value of column. The loop continues to execute until column reaches the value of -1. At the end of the for loop, z is already 11. Loop once more on the first for statement. The two inner loops are alternately executed depending if row is an even or odd number. Until we reach 0 for the value of row, it will exit on its scope of the loop and loop back at while statement. Testing the condition on while becomes false because the value of z is already 26. This will cause an exit on its own block. The next set of for loops are just used to display the content of each cell of array x. The idea here is to move on the next line count of column reaches 5. The output of the program is generated.

129


130


EXERCISE 8 I. Program Simulation Simulate: Determine the output 1. public class SimulateEx20 { public static void main(String[] args) { int[] mysteryNum = new int[25]; int ctr = 0, i, x; while(ctr < mysteryNum.length) { mysteryNum[ctr]=ctr+1; ctr++; } i=0; do { for(x = 1; x <= 5; x++) { System.out.print(mysteryNum[i] + "\t"); i++; } System.out.println(); } while (i < mysteryNum.length); } } 2. public class SimulateEx21 { public static void main(String[] args) { int[][] numero = {{1,4,3,2,5},{3,3,10,10,1}}; int ctr = 0, i; for (ctr = 0; ctr < numero.length; ctr++) { for(i = 0; i < numero[ctr].length; i++) {

131


System.out.print(numero[ctr][i] + "\t"); } System.out.println(); } } } 3. public class SimulateEx22 { public static void main (String [] args) { int[][] num = new int[3][3]; int x,y; x = 0; while (x < 3) { for (y = 2; y > -1; y--) { num[x][y]= x + y; } x++; } y = 0; while (y < 3) { for (x = 2; x > -1; x--) { System.out.print(num[x][y] + "\t"); } System.out.println(); y++; } } } 4. public class SimulateEx23 { public static void main(String[] args) { int[] number = {1,3,5,7}; int[] numero = {8,6,4,2};

132


int x, y, value = 0, sum = 0; for (x = 0; x < number.length; x++) { for (y = 3; y > -1; y--) { value = number[x] * numero[y]; sum += value; System.out.print(value + "\t"); } System.out.println(); } System.out.println("\nSum is " + sum); } } 5. public class SimulateEx24 { public static void main(String[] args) { int row, col; int[][] num = new int[4][4]; int number = 4; for (row = 0; row < num.length; row++) { for (col = 0; col < num[row].length; col++) { num[row][col] = number; number--; } number += 5; }

for (int m = num.length - 1; m >= 0; m--) { for (int n = 0; n < num[m].length; n++) { System.out.print(num[m][n] + "\t"); } System.out.println(); } } }

133


II. Programming Exercise 1. Design program TopSportsMan in HBO pay per view that displays the list of athlete with their sales. The user has an option to enter the top 5 athlete’s name and sales. Compute its total sales at the end. Sample Input / Output: Enter athlete 1: Pacman Enter sales: 2368921.12 Enter athlete 2: Serena Enter sales: 987652.90 Enter athlete 3: Phelps Enter sales: 125657.56 Enter athlete 4: Wade Enter sales: 1568231.3 Enter athlete 5: Woods Enter sales: 789236.89 Top SportsMan Name Sales =================================== Pacman $2,368,921.12 Serena $987,652.90 Phelps $125,657.56 Wade $1,568,231.30 Woods $789,236.89 =================================== Total $5,839,699.77 2. Formulate two-dimensional array-oriented program TwoDimMatrix that will produce the given output. Use SimulateEx19 as a guide to formulate your own solution. Sample Output: 1 2 3 4 5

10 9 8 7 6

11 12 13 14 15

20 19 18 17 16

21 22 23 24 25

3. Create program LuckyColor that allows user to guess the lucky color generated by the computer. Import class Random to make use of the method nextInt() that will generate integer random numbers. To import Random class:

134


import java.util.Random; To declare an object using Random class ( where n is the name of the object), use: Random n = new Random(); To generate random integers and assign it at lucky integer variable: int lucky = n.nextInt(3); lucky variable may have (or generate) values from 0 to 2 (3 numbers, 3 is not included). Sample Input/Output: Guess color [1-Red, 2-Green, 3-Blue]: 1 Try again! lucky color is green Guess color [1-Red, 2-Green, 3-Blue]: 2 Correct. The lucky color is green 4. Create array-oriented program ScissorPaperRock that allows player to play with computer’s random move on choices. Scissor wins over paper and rock; paper wins over rock; rock wins over scissor. Make the program indefinite until player wins. Sample Input/Output: Enter your number move [1=Scissor, 2=Paper, 3=Rock]: 2 Your move is Paper Computer move is Scissor You lose! Try again! Enter your number move [1=Scissor, 2=Paper, 3=Rock]: 1 Your move is Scissor Computer move is Scissor Draw! Enter your number move [1=Scissor, 2=Paper, 3=Rock]: 3 Your move is Rock Computer move is Rock Draw! Enter your number move [1=Scissor, 2=Paper, 3=Rock]: 3 Your move is Rock Computer move is Paper You lose! Try again!

135


Enter your number move[ 1=Scissor, 2=Paper, 3=Rock]: 1 Your move is Scissor Computer move is Paper You win!

136


SOLUTION TO SELECTED SAMPLE EXERCISES EXERCISE 2 1. package javaPackage; public class Dream { public static void main(String[] args) { System.out.println("This is my quest!"); System.out.println("To\tfollow\t\tthe\tstar"); System.out.println("\tNo matter how hopeless"); System.out.println("No matter how far"); } }

3. package javaPackage; public class Victor { public static void main(String[] args) { System.out.print("Life's battles don't always go\n" + "\tTo the stronger or faster man.\n" + "But sooner or later,\tthe man who wins\n"+ "Is the man who thinks\the\tcan."); } } EXERCISE 3 I. 1. TRUE. 3. FALSE. Variable should not start with number. It can be re-written as $4TheWin or _4TheWin.

137


5. FALSE. Can be written in quantitySold or quantity_Sold. No space allowed.FALSE. Java reserved word. 7. FALSE. Java reserved word. II. 1. float price; or double price; 3. float distanceCovered; or double distance_Covered; EXERCISE 4 I. 1.

areaTriangle = 1/2*base*height; or areaTriangle = (base*height) / 2; or areaTriangle = 1/2*base*height; = 1/2*10*2 = 0.5 * 10 * 2 =5*2 = 10

3.

m = principal*(1+i)*(1+i)*(1+i); = 1000 *(1+0.05)* (1+0.05)* (1+0.05) = 1000*(1.05)*(1.05)*(1.05) = 1050*(1.05)*(1.05) = 1102.5* (1.05) = 1157.625

5.

c = a + b % 4 – (b – a*3); = 2 + 10 % 4 – (10 – 2*3) = 2 + 2 – (10 – 6) =2+2–4 =4–4 =0

II.

138


1. unitPrice *= 0.5; 3. fee -= discount; III. 1. package javaPackage; import java.util.Scanner; import java.text.DecimalFormat; public class Rectangle { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("#,###.00"); double length =0.0, width = 0.0; double perimeter = 0.0, area = 0.0; System.out.print("Enter length: "); length = input.nextDouble(); System.out.print("Enter width: "); width = input.nextDouble(); perimeter= 2*(length + width); area = length * width; System.out.println("\nPerimeter is " + df.format(perimeter) + " meters"); System.out.println("Area is " + df.format(area) + " meters"); } } 3. package javaPackage; import java.util.Scanner; public class Age { public static void main(String[] args) {

139


Scanner input = new Scanner(System.in); String name=""; int currentYear=0, birthYear=0; int age=0; System.out.print("Enter name: "); name=input.nextLine(); System.out.print("Enter current year: "); currentYear=input.nextInt(); System.out.print("Enter birth year: "); birthYear=input.nextInt(); // Compute age age = currentYear - birthYear; //Display the output System.out.println("\n" + name + ", your age on " + currentYear + " is " + age); } }

5. package javaPackage; import java.util.Scanner; import java.text.DecimalFormat; public class Washer { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("###.00"); double side=0.0; double areaSquare=0.0; double diameter, areaCircle=0.0; double areaWasher=0.0; System.out.print("Enter s: "); side = input.nextDouble();

140


areaSquare = side * side; // area of square //Determine the diameter of the circle diameter =side - 2*0.05*side; //Compute the area of circle areaCircle = 3.1416*(diameter/2.0)*(diameter/2.0); //Deduct the are of square from circle areaWasher = areaSquare - areaCircle; //Display the result System.out.println("\nArea of the washer is " + df.format(areaWasher) + " millimeters"); } } EXERCISE 5 I. 1.

3.

141


II. 1. import java.util.Scanner; public class AgeGroup { public static void main(String[] args) { Scanner input = new Scanner(System.in); int age = 0; String ageDesc = ""; System.out.print("Enter age: "); age=input.nextInt(); if (age>=60) { ageDesc = "Senior"; } else if ((age <= 59) && (age >= 31)) { ageDesc = "Adult"; } else if ((age <= 30) && (age >= 18)) { ageDesc = "Young Adult"; }

142


else if ((age <= 17) && (age >= 1)) { ageDesc = "Under age"; } else { ageDesc = "Invalid age"; } System.out.println("\n"+ageDesc); } } 3. import java.util.Scanner; import java.text.DecimalFormat; public class AverageGrade { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("###.00"); String name="", gradeStatus=""; double physics=0.0, algebra=0.0, program=0.0; double average=0.0; System.out.print("Enter name: "); name = input.nextLine(); System.out.print("Enter grade in Physics: "); physics=input.nextDouble(); System.out.print("Enter grade in Algebra: "); algebra=input.nextDouble(); System.out.print("Enter grade in Programming: "); program=input.nextDouble(); average=(physics + algebra + program)/3.0; if (average <= 100) { if (average >= 95) {

143


gradeStatus = "President lister"; } } else if (average <= 94) { if (average >=89) { gradeStatus = "Dean lister"; } } else if (average <= 88) { if (average >= 83) { gradeStatus = "Average Student"; } } else if (average <= 82) { if (average >= 78) { gradeStatus = "Fair"; } } else if (average < 78) { gradeStatus = "Failure"; } else { gradeStatus = "Invalid grade"; } System.out.println("\n" + name + " average grade is " + df.format(average)); System.out.println(gradeStatus); } } EXERCISE 6 I. Program Simulation 1.

144


3.

145


II. Programming Exercise 1. package javaPackage; public class EvenSquareCube { public static void main(String[] args) { int n, ctr = 1; int square = 0, cube = 0; int totalSquare = 0, totalCube = 0;

System.out.println("\nInteger\tSquare\tCube\n"); while (ctr <= 10) { if ((ctr % 2) == 0) { square = ctr * ctr; cube = square * ctr; totalSquare += square; totalCube += cube; System.out.println(ctr + "\t" + square + "\t" + cube); } ctr++; } System.out.println("\nTotal\t" + totalSquare + "\t" + totalCube); } } 3. package javaPackage; public class RowColNumber { public static void main(String[] args) { int row, col; int num = 25, dispNum = 0; for (row=1; row <= 5; row++) { dispNum = num; for(col=1; col <= 5; col++) { System.out.print(dispNum + "\t");

146


dispNum -= 5; } num--; System.out.println(); } } } EXERCISE 7 I. Program Simulation 1.

3.

147


II. Programming Exercise 1. import java.util.Scanner; import java.text.DecimalFormat; public class RectangleMethod { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("#,###.00"); double length =0.0, width = 0.0; double perimeter = 0.0, area = 0.0; System.out.print("Enter length: "); length = input.nextDouble(); System.out.print("Enter width: "); width = input.nextDouble(); perimeter= calculatePerimeter(length, width); area = calculateArea(length, width);

148


System.out.println("\nPerimeter is " + df.format(perimeter) + " meters"); System.out.println("Area is " + df.format(area) + " meters"); } public static double calculatePerimeter(double strip1, double strip2) { return 2 * (strip1 + strip2); } public static double calculateArea(double dimension1, double dimension2) { return dimension1 * dimension2; } } 3. import java.util.Scanner; public class Dozen { public static void main(String[] args) { System.out.println(displayDozen()); } public static String displayDozen() { Scanner input = new Scanner(System.in); String output = ""; int eggs = 0; System.out.print("Enter the number of eggs: "); eggs = input.nextInt(); output += "\nNumber of dozen: "; output += determineDozen(eggs); output += "\nEggs less than a dozen: "; output += showLessDozen(eggs); return output; } public static int determineDozen(int yolk)

149


{ return yolk / 12; } public static int showLessDozen(int e) { return e % 12; } } 5. import java.util.Scanner; public class Dec2Binary { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number = 0; System.out.print("Enter number: "); number = input.nextInt(); System.out.println("Binary equivalent is " + convert2Binary(number)); } public static String convert2Binary(int n) { int remainder=0; String binNumber=""; while(n >= 1) { remainder = n % 2; binNumber += remainder; n = n / 2; } return reverseText(binNumber); } public static String reverseText(String num) { String reverseStr = ""; int size = num.length(); int ctr = size-1; while(ctr >= 0) {

150


reverseStr += num.substring(ctr,ctr+1); ctr--; } return reverseStr; } } 7. import java.util.Scanner; public class TriangleMethod { public static void main(String[] args) { Scanner input = new Scanner(System.in); int base = 0; System.out.print("Enter base of figure: "); base = input.nextInt(); System.out.println(); System.out.println(generateFigure(base)); } public static String generateFigure(int b) { int x, y; String output = ""; x = 1; while (x <= b) { for (y = 1; y <= x; y++) { output += "$"; } output += "\n"; x++; } return output; } }

151


EXERCISE 8 I. Program Simulation 1.

152


3.

II. Programming Exercise 1. import java.util.Scanner; import java.text.DecimalFormat; public class TopSportsMan { public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat df = new DecimalFormat("$##,####,###.00"); String[] name = new String[5]; double[] sales = new double[5]; double totalSales = 0.0; int ctrAth; for (ctrAth = 0; ctrAth < 5; ctrAth++) { System.out.print("\nEnter athlete " + (ctrAth + 1) + ": "); name[ctrAth] = input.next(); System.out.print("Enter sales: "); sales[ctrAth] = input.nextDouble();

153


totalSales += sales[ctrAth]; } // Print Header texts System.out.println("\nTop SportsMan"); System.out.println("Name\t\t\tSales"); System.out.println("==================================="); // Print Detail for(ctrAth = 0; ctrAth < 5; ctrAth++) { System.out.println(name[ctrAth] + "\t\t\t" + df.format(sales[ctrAth])); } // Print total System.out.println("==================================="); System.out.println("Total\t\t\t" + df.format(totalSales)); } } 3. import java.util.Scanner; import java.util.Random; public class LuckyColor { public static void main(String[] args) { Scanner input = new Scanner(System.in); Random n = new Random(); String[] color = {"red", "green", "blue"}; int guessColor = 0; while(true) { System.out.print("Guess color [1-Red, 2-Green, 3-Blue]: "); guessColor = input.nextInt(); int lucky = n.nextInt(3); if (lucky ==(guessColor-1)) { System.out.println("Correct. The lucky color is "+ color[lucky]); break; }

154


else { System.out.println("Try again! lucky color is "+ color[lucky]); } System.out.println(); } } }

155


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.