You are on page 1of 15

KING ABDULAZIZ UNIVERSITY

Faculty of Computing & Information Technology Department of Computer Science

Lab Manual
CPCS203 Programming II
(Object-oriented)
1432/1433H

Lab - 6
Learning Procedure

1) 2) 3) 4)

Stage J (Journey inside-out the concept) Stage a1 (apply the learned) Stage v (verify the accuracy) Stage a2 (assess your work)

Term I 2011

Lab-6: Repetition Statements

Laboratory 6:
Statement Purpose:
This lab will give you practical implementation of different types of Repetition Statements (loops) and defining custom class in java.

Activity Outcomes:
This lab teaches you the following topics: Implement repetition control in a program using (while, do while, for loop structure) and break statement. Nest a loop repetition statement inside another repetition statement. Describe how the reserved word this is used Define overloaded methods and constructors Describe how the arguments are passed to the parameters using the pass-by-value scheme.

Instructor Note:
As pre-lab activity, read Chapter 6 and 7 from the book (An Introduction to Object-Oriented Programming with Java, 4th Edition by C. THOMAS WU (Books website www.mhhe.com/wu), and also as given by your theory instructor.
Names I.D.

1. .... 2. .... 3. .... 4. ...

...

CPCS203 The Lab Note

Lab-6

Term I 2011

Lab-6: Repetition Statements

1) Stage J (Journey) Introduction


One of the great virtues of computers is that they will repeat mindless tasks without complaint. To facilitate such repetition, Java includes statements types called loops, which allow a program to specify some sequence of instructions that should be repeated. Within an instance method or a constructor, this is a reference to the current object the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism.

2) Stage a1 (apply) Lab Activities:


Activity 1:
Java Palindrome Number Example, This Java Palindrome Number Example shows how to find if the given number is palindrome number or not. For example 7887 is a Palindrome number because the number is remains same either your read it from left to right or from right to left.

Solution:
A. Create Java Main Class and named it PalindromeNumberExample B. Copy the Code and test it by running the application
public class PalindromeNumberExample { public static void main(String[] args) { //int number = use scanner to read the number from user int number=7887; int numbertemp=number; int reversedNumber = 0; int temp=0; while (numbertemp > 0){ CPCS203 The Lab Note Lab-6
2

Term I 2011

Lab-6: Repetition Statements

temp = numbertemp % 10; numbertemp = numbertemp / 10; reversedNumber = reversedNumber * 10 + temp; } // to check if the number is palindrome or not if (number == reversedNumber) System.out.println(number + " is a palindrome number"); else System.out.println(number + " is not a palindrome number"); } }

Activity 2:
Example shows how to generate pyramid or triangle like given below using for loop based on the given size of pyramid. 1 12 123 1234 12345

Solution:
A. Create Java Main Class and named it JavaPyramid1 B. Copy the Code and test it by running the application
public class JavaPyramid1 { public static void main(String[] args) { for(int i=1; i<= 5 ;i++){ for(int j=0; j < i; j++){ System.out.print(j+1); } System.out.println(""); } } }

Break is often used in terminating for loop but it can also be used for terminating other loops as well such as while, do while etc. . Break is a tool inside Java branching category.

CPCS203 The Lab Note

Lab-6

Term I 2011

Lab-6: Repetition Statements

Activity 3:
The example below, how to terminate the while loop is demonstrated. In the program we breaking while loop when the user enter choice ==stop and value0 == true.
import javax.swing.JOptionPane; public class Java_Break_While { public static void main(String args[]) { String str = "stop", choice = "", strb = ""; boolean value = true; String value0 = "true"; while (value) { choice = JOptionPane.showInputDialog(null, "Type 'stop'", "Input box ", 1); strb = JOptionPane.showInputDialog(null, "Type boolean 'true'", "Input box ", 1); if(choice.equals(str) && strb.equals(value0)){ JOptionPane.showMessageDialog(null, "Well ! now you have break the \n\t\twhile loop \n\t\tSuccessfully", "Congrats ", 1); break ; } else JOptionPane.showMessageDialog(null, "Type correct value", "Alert ", 1); } } }

Activity 4:
Practical Learning: Passing Arguments 1. Start NetBeans 2. Create a New Project as a Java Application and name it Geometry2 3. In the Projects window, under Geometry2, expand Sources Packages if necessary. To create a new class, under the Geometry2 folder, right-click the Geometry2 sub-folder -> New -> Java Class... 4. Set the Name to Cylinder and click Finish Change the file as follows:
CPCS203 The Lab Note Lab-6
4

Term I 2011

Lab-6: Repetition Statements

package geometry2; import java.util.Scanner; public class Cylinder { double specifyRadius() { double rad; Scanner scnr = new Scanner(System.in); System.out.print("Radius: "); rad = scnr.nextDouble(); return rad; } double specifyHeight() { double h; Scanner scnr = new Scanner(System.in); System.out.print("Height: "); h = scnr.nextDouble(); return h; } double calculatebaseArea(double rad) { return rad * rad * 3.14159; } double calculateLateralArea(double rad, double hgt) { return 2 * 3.14159 * rad * hgt; } double calculateTotalArea(double rad, double hgt) { return 2 * 3.14159 * rad * (hgt + rad); } double calculateVolume(double rad, double hgt) { return 3.14159 * rad * rad * hgt; } void process() { double radius; double height; double baseArea; double lateralArea; double totalArea; double volume; System.out.println("Enter the dimensions of the cylinder"); radius = specifyRadius(); height = specifyHeight(); CPCS203 The Lab Note Lab-6
5

Term I 2011

Lab-6: Repetition Statements baseArea = calculatebaseArea(radius); lateralArea = calculateLateralArea(radius, height); totalArea = calculateTotalArea(radius, height); volume = calculateVolume(radius, height); System.out.println("\nCylinder Characteristics"); System.out.printf("Radius: %g\n", radius); System.out.printf("Height: %g\n", height); System.out.printf("Base: %f\n", baseArea); System.out.printf("Lateral: %f\n", lateralArea); System.out.printf("Total: %f\n", totalArea); System.out.printf("Volume: %f\n", volume); }

5. Access the Main.java file and change it as follows:


package geometry2; public class Main { static void main(String[] args) { Cylinder cyl = new Cylinder(); cyl.process(); } }

6. Execute the application to test it. Here is an example: Enter the dimensions of the cylinder Radius: 35.95 Height: 30.25 Cylinder Radius: Height: Base: Lateral: Total: Volume: Characteristics 35.9500 30.2500 4060.198770 6832.879710 14953.277250 122821.012792

CPCS203 The Lab Note

Lab-6

Term I 2011

Lab-6: Repetition Statements

Activity 5:
Method Overloading In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. // the following example demonstrate the method overloading in OOP (Java). Step 1: Create a java class and name it OverloadDemo
class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } }

Step 2: Now create main java class and name it Overload


public class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.2); System.out.println("Result of ob.test(123.2): " + result); } } CPCS203 The Lab Note Lab-6
7

Term I 2011

Lab-6: Repetition Statements

As you can see, test( ) is overloaded four times. The first version takes no parameters, the second takes one integer parameter, the third takes two integer parameters, and the fourth takes one double parameter. The fact that the fourth version of test( ) also returns a value is of no consequence relative to overloading, since return types do not play a role in overload resolution. When an overloaded method is called, Java looks for a match between the arguments used to call the method and the method's parameters.

Activity 6:
Using the this Keyword:

Within an instance method or a constructor, this is a reference to the


current object

The most common reason for using the this keyword is because a field is
shadowed by a method or constructor parameter.

You can also use the this keyword to call another constructor in the
same class. // the following example demonstrate the use of this and constructor overloading in OOP (Java). Step 1: Create a java class and name it Rectangle
class Rectangle{ int x,y,width,height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } CPCS203 The Lab Note Lab-6
8

Term I 2011

Lab-6: Repetition Statements

void show(int width, int height){ this.width = width; this.height = height; } int calculate(){ return(width*height); } }

Step 2: Now create main java class and name it UseOfThisOperator


public class UseOfThisOperator{ public static void main(String[] args){ Rectangle rectangle=new Rectangle(); rectangle.show(5,6); int area = rectangle.calculate(); System.out.println("The area of a Rectangle is area); }

" +

3) Stage v (verify) Home Activities:


1. Use nested loops that print the following patterns in three separate programs.

2. (Printing numbers in a pyramid pattern) Write a nested for loop that prints the following output:

CPCS203 The Lab Note

Lab-6

Term I 2011

Lab-6: Repetition Statements

1 1 2 1 1 2 4 2 1 1 2 4 8 4 2 1 1 2 4 8 16 8 4 2 1 1 2 4 8 16 32 16 8 4 2 1 1 2 4 8 16 32 64 32 16 8 4 2 1 1 2 4 8 16 32 64 128 64 32 16 8 4 2 1 3. Write a Java program to generate Fibonacci Series like given below using loop up to given number by user. If user enter number = 20, your output must be Fibonacci Series upto 20 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 [Hint: add the last two number in the series to get new number of the series] 4. Write a program that prompts the user to enter the number of students and each student's name and score, and finally displays the student with the highest score. 5. Write a program that displays all the numbers from 100 to 1000, ten per line, that are divisible by 5 and 6. 6. Complete the first four constructors of the following class. Each of the four constructors calls the fifth one by using the reserved word this.
Class Cat{ private static final String DEFAULT_NAME = "No Name"; private static final int DEFAULT_HGT = 6; private static final double DEFAULT_WGT = 10.0; private String name; private int height; private double weight; public Cat() { // assign defaults to all data members } public Cat(String name) { // assign the passed name to the data member // use defaults for height and weight } public Cat(String name, int height) { // assign the passed name to the name and height // use defaults for weight CPCS203 The Lab Note Lab-6
10

Term I 2011

Lab-6: Repetition Statements }

public Cat(String name, double weight) { // assign the passed name to the name and weight // use defaults for height } public Cat(String name, int height, double weight) { this.name = name; this.height = height; this.weight = weight; } }

(Extra) Home Activities:


Some more Practical Learning: Overloading a Method:

Activity 7:
1. Start a new Java Application named MomentOfInertia1

2. Change the file as follows:


package momentofinertia1; import java.util.Scanner; public class Main { // Rectangle static double calculateMomentOfInertia(double b, double h) { return b * h * h * h / 3; } static void main(String[] args) { CPCS203 The Lab Note Lab-6

11

Term I 2011

Lab-6: Repetition Statements double base, height; Scanner scnr = new Scanner(System.in);

System.out.println("Enter the dimensions of the Rectangle"); System.out.print("Base: "); base = scnr.nextDouble(); System.out.print("Height: "); height = scnr.nextDouble(); System.out.println("\nMoment of inertia with " + "regard to the X axis: "); System.out.printf("I = %.2fmm", calculateMomentOfInertia(base, height)); } }

3. Execute the application. Here is an example of running the program: Enter the dimensions of the Rectangle Base: 2.44 Height: 3.58 Moment of inertia with regard to the X axis: I = 37.317939mm

Activity 8:
1. A circle, and thus a semi-circle, requires only a radius. Since the other version of the calculateMomentOfInertia() function requires two arguments, we can overload it by providing only one argument, the radius. To overload the above calculateMomentOfInertia() method, type the following in the file:

package momentofinertia1; import java.util.Scanner; CPCS203 The Lab Note Lab-6

12

Term I 2011

Lab-6: Repetition Statements

public class Main { // Rectangle static double calculateMomentOfInertia(double b, double h) { return b * h * h * h / 3; } // Semi-Circle static double calculateMomentOfInertia(double R) { final double PI = 3.14159; return R * R * R * R * PI/ 8; } static void main(String[] args) { double radius; double base, height; Scanner scnr = new Scanner(System.in); System.out.println("Enter the dimensions of the Rectangle"); System.out.print("Base: "); base = scnr.nextDouble(); System.out.print("Height: "); height = scnr.nextDouble(); System.out.println("\nMoment of inertia with " + "regard to the X axis: "); System.out.printf("I = %fmm", calculateMomentOfInertia(base, height)); System.out.print("\nEnter the radius: "); radius = scnr.nextDouble(); System.out.println("Moment of inertia of a semi-circle " + "with regard to the X axis: "); System.out.printf("I = %fmm", calculateMomentOfInertia(radius)); } }

CPCS203 The Lab Note

Lab-6

13

Term I 2011

Lab-6: Repetition Statements

4) Stage a2 (assess) Homework 6:


For this lab you are requested to solve Lab homework and to submit it before the deadline.

Lab Homework:
The laboratory homework of this lab (and also all the following labs in this manual) should include the following items/sections: A cover page with your name, course information, lab number and title, and date of submission. Programming: a brief description of the process you followed in conducting the coding of the homework solution. Results obtained throughout the written code followed with brief analysis of these results. A zip file including both the Java project folder and the work file contains all items/sections above.

Lab Report:
The laboratory report of this lab (and also all the following labs in this manual) should include the following items/sections: A cover page with your name, course information, lab number and title, and date of submission. A summary of the addressed topic and objectives of the lab. Implementation: a brief description of the process you followed in conducting the implementation of the lab scenarios. Results obtained throughout the lab implementation, the analysis of these results, and a comparison of these results with your expectations. Answers to the given exercises at the end of the lab. If an answer incorporates new graphs, analysis of these graphs should be included here. A conclusion that includes what you learned, difficulties you faced, and any suggested extensions/improvements to the lab. Note: only a softcopy is required for both homework and report, please do not print or submit a hard copy.

CPCS203 The Lab Note

Lab-6

14

You might also like