Professional Documents
Culture Documents
Lab Manual: CPCS203 Programming II
Lab Manual: CPCS203 Programming II
Lab Manual
CPCS203
Programming II
(Object-oriented)
1432/1433H
Lab - 6
Learning Procedure
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
(Book’s website www.mhhe.com/wu), and also as given by your theory
instructor.
Names I.D.
1. .……………..………………………………. ………………………………
2. ..…………………………………………….. ………………………………
3. .……………………………………………... ………………………………
4. .…………………………………………….. ..…………………………….
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.
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
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. .
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;
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
package geometry2;
import java.util.Scanner;
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;
}
void process() {
double radius;
double height;
double baseArea;
double lateralArea;
double totalArea;
double volume;
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);
}
}
package geometry2;
cyl.process();
}
}
Cylinder Characteristics
Radius: 35.9500
Height: 30.2500
Base: 4060.198770
Lateral: 6832.879710
Total: 14953.277250
Volume: 122821.012792
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.
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:
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.
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;
}
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:
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
}
Activity 7:
1. Start a new Java Application named MomentOfInertia1
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;
// Semi-Circle
static double calculateMomentOfInertia(double R) {
final double PI = 3.14159;
return R * R * R * R * PI/ 8;
}
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.