0% found this document useful (0 votes)
5 views

CMPE211labManualV20

Cmpe

Uploaded by

Zeynep Bayram
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

CMPE211labManualV20

Cmpe

Uploaded by

Zeynep Bayram
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CMPE-211

OBJECT ORIENTED PROGRAMMING


LAB MANUAL
Release V20

Hakan ALTINÇAY
CMPE – 211
Preliminary Work (Pre-Lab Activity)
Laboratory Experiment # 1
Textbook Material: Chapter 1 «Introduction to Java»
Chapter 2 «Elementary Programming»

••• Tutorial
The Tutorial covers introduction to Eclipse IDE, which is used in all following laboratory experiments. Tutorial is
conducted by one of the Course Lab. assistants who guides Your laboratory group. Explanations are based on
the Supplement 2f.
Main topics to cover during 1-hour tutorial:
• how to Eclipse Integrated Development Environment (IDE),
• how to create, compile and execute Java console application,
• how to use debugger to locate logical errors in programs,
All these skills are essential for performing successfully upcoming lab tasks.
Read the supplement in advance (before entering the Lab).

••• Example
 Write (copy), Modify, Compile, Execute and Debug Java program covered by the following example:

Example

import java.util.Scanner;

public class RepeatAdditionQuiz {


public static void main(String[] args) {
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);

// Create a Scanner
Scanner input = new Scanner(System.in);

System.out.print(
"What is " + number1 + " + " + number2 + "? ");
int answer = input.nextInt();

while (number1 + number2 != answer) {


System.out.print("Wrong answer. Try again. What is "
+ number1 + " + " + number2 + "? ");
answer = input.nextInt();
}

System.out.println("You got it!");


}
}

••• TASK 1
The constant  that is also known as Archimedes’ constant was used by Egyptians but an accurate approximation
was not available (it was approximated as 3.1605). In the 5th century AD, Chinese
mathematics approximated it to seven digits, while Indian mathematics made a five-digit approximation, both
using geometrical techniques. Around 250BC, the Greek mathematician Archimedes found that it is in the interval
(223/71,22/7). Archimedes knew, what so many people to this day do not, that it is not equal 22/7, and made
no claim to have discovered the exact value. The 14 correct digits were computed in 15th century and 527 correct
digits were computed in 19th century. Write, Compile and Execute a Java program that approximately calculates
 using the following expression, by considering 15 terms:

••• TASK 2
Write, Compile and Execute a Java program that reads an investment amount, annual interest rate and
number of years and displays the future investment value using the following formula:

futureInvestmentValue = investmentAmount x (1 + montlyInterestRate)numberOfYears x 12

For example, if you enter amount 1000, annual interest rate 3.25% and the number of years 1, the future
value is 1032.98. Here is a sample run:

• NOTE: Use pow method in Math class (see page 70).

••• Sources
• Introduction to Java Programming and Data Structures, Comprehensive Version, 11 th Edition, Y. D. Liang,
Pearson, 2019.
CMPE – 211
Preliminary Work (Pre-Lab Activity)
Laboratory Experiment # 2
Textbook Material: Chapter 3 «Selections»
Chapter 4 «Mathematical Functions, Characters and Strings»
Chapter 5 «Loops»

••• TASK 1
Write, Compile and Execute a Java program that prompts the user to enter a point (x, y) and checks whether
the point is within the circle centered at (0, 0) with radius 10. For example, (4, 5) is inside the circle and (9, 9)
is outside the circle, as shown in Figure below. (Hint: A point is in the circle if its distance to (0, 0) is less than
or equal to 10. The formula for computing the distance is the square root of ((x2 - x1)2 + (y2 - y1)2). Test your
program to cover all cases.)

Two sample runs are shown below.

••• TASK 2
A problem that was defined in the 13th century can be summarized as follows. A newborn pair of rabbits (one
male and one female) are put onto an island. Rabbits mate at age of one month and they have a one month
gestation period (the time interval each rabbit spends inside the uterus of its mother). We assume that the
rabbits do not die and, from second month on, each female produces a one new male and one new female rabbit.
The following figure shows the number of rabbits on the island after 4 months.
FIRST DAY:

AT THE END OF FIRST MONTH: BECAME MATURE TO MATE:

AT THE END OF SECOND MONTH

AT THE END OF THIRD MONTH


AT THE END OF FOURTH MONTH

Write, Compile and Execute a Java program that computes the number of rabbit pairs on the island at the end
of 24 months. What is the name of the mathematician who defined the problem?

Notice that the patterns of consecutive numbers obtained are also seen in the nature. For instance, you will find
that, after some months, 21 pairs will be available. The next month, there will be 34 rabbit pairs. In fact, these
are the numbers of seeds found in a sunflower when counted from left to right and right to left.

••• TASK 3
The Persian mathematician Al-Karaji (953–1029) computed the first description of Pascal's triangle given below.
It was later repeated by the Persian poet-astronomer-mathematician Omar Khayyám (1048–1131); thus the
triangle is also referred to as the Khayyam triangle in Iran.

The Pascal's triangle determines the coefficients which arise in binomial expressions. For example, consider the
expansion
(x + y)2 = x2 + 2xy + y2 = 1x2y0 + 2x1y1 + 1x0y2.
The coefficients of the terms are in the third row of the triangle. As a general approach, In general, when x + y is
raised to a positive integer power we have:
(x + y)n = a0xn + a1xn−1y + a2xn−2y2 + ... + an−1xyn−1 + anyn,

where the coefficients ai in this expansion are precisely the numbers on row (n+1) of Pascal's triangle. Each row
of the triangle can be computed by adding the pairs of numbers in the previous row from left to right. Write,
Compile and Execute a Java program that prints the Pascal’s triangle given above.

••• TASK 4
Write, Compile and Execute a Java program based on a user-defined function that computes the sum of first
and last digits of a given number that is composed of two or more digits (e.g. 23, -145, 3900, etc.).

••• Sources
• Introduction to Java Programming and Data Structures, Comprehensive Version, 11 th Edition, Y. D. Liang,
Pearson, 2019.
CMPE – 211
Preliminary Work (Pre-Lab Activity)
Laboratory Experiment # 3
Textbook Material: Chapter 6 «Methods»

••• TASK 1
Write, Compile and Execute a Java method that computes the sum of the digits in an integer. Use the following
method header:

public static int sumDigits(long n)

For example, sumDigits(234) returns 9 (2 + 3 + 4). (Hint: Use the % operator to extract digits, and the /
operator to remove the extracted digit. For instance, to extract 4 from 234, use 234 % 10 (= 4). To remove 4
from 234, use 234 / 10 (= 23). Use a loop to repeatedly extract and remove the digit until all the digits are
extracted. Write a test program that prompts the user to enter an integer and displays the sum of all its digits.

••• TASK 2
Write, Compile and Execute the Java methods with the following headers to check if a number is a palindrome:

// Return the reversal of an integer


public static int reverse(int number)

// Return true if number is a palindrome


public static boolean isPalindrome(int number)

For example, reverse(3456) displays 6543. Use the reverse method to implement isPalindrome. A number
is a palindrome if its reversal is the same as itself. Write a test program that prompts the user to enter an integer
and reports whether the integer is a palindrome.

••• TASK 3
In number theory, a happy number is a number which eventually reaches 1 when replaced by the sum of the
square of each digit. For instance, 13 is a happy number because

On the other hand, 4 is not a happy number because the sequence starting with

and eventually reaches to 4 that is the number that started the sequence, and so the process continues in an
infinite cycle without ever reaching 1.

Write, Compile and Execute a Java method that computes whether a given number is happy or sad.

••• Sources
• Introduction to Java Programming and Data Structures, Comprehensive Version, 11 th Edition, Y. D. Liang,
Pearson, 2019.
CMPE – 211
Preliminary Work (Pre-Lab Activity)
Laboratory Experiment # 4
Textbook Material: Chapter 7 «Single-Dimensional Arrays»
Chapter 8 «Multidimensional Arrays»

••• TASK 1
Write a Java method that returns a new array by eliminating the duplicate values in the array using the following
method header:

public static int[] eliminateDuplicates(int[] list)

Write a Java test Program that reads in ten integers, invokes the method, and displays the result. Here is the
sample run of the program:

••• TASK 2
Write a Java method that merges two sorted lists into a new sorted list.

public static int[] merge(int[] list1, int[] list2)

Write a Java test Program that prompts the user to enter two sorted lists and displays the merged list. Here is a
sample run. Note that the first number in the input indicates the number of the elements in the list. This number
is not part of the list.

••• TASK 3
Write a Java method that returns the location of the largest element in a two-dimensional array.

public static int[] locateLargest(double[][] a)

The return value is a one-dimensional array that contains two elements. These two elements indicate the row
and column indices of the largest element in the two-dimensional array. Write a Java test Program that prompts
the user to enter a two- dimensional array and displays the location of the largest element in the array.

Here is a sample run:


••• TASK 4
Given a set of cities, the central city is the city that has the shortest total distance to all other cities. Write,
Compile and Execute a Java program that prompts the user to enter the number of the cities and the locations
of the cities (coordinates), and finds the central city and its total distance to all other cities.

••• Sources
• Introduction to Java Programming and Data Structures, Comprehensive Version, 11th Edition, Y. D. Liang,
Pearson, 2019.
CMPE – 211
Preliminary Work (Pre-Lab Activity)
Laboratory Experiment # 5
Textbook Material: Chapter 9 «Objects and Classes»
Chapter 10 «Object-Oriented Thinking»

••• TASK 1
Design a Java class named Rectangle to represent a rectangle. The class contains:

✓ Two double data fields named width and height that specify the width and height of the rectangle. The
default values are 1 for both width and height.
✓ A no-arg constructor that creates a default rectangle.
✓ A constructor that creates a rectangle with the specified width and height.
✓ A method named getArea() that returns the area of this rectangle.
✓ A method named getPerimeter() that returns the perimeter.

Write a Java test program that creates two Rectangle objects—one with width 4 and height 40 and the other
with width 3.5 and height 35.9. Display the width, height, area, and perimeter of each rectangle in this order.

••• TASK 2
Design a Java class that is named as MyInteger. The class should contain:

✓ An int data field named value that stores the int value represented by this object.
✓ A constructor that creates a MyInteger object for the specified int value.
✓ A getter method that returns the int value.
✓ The methods isEven(), isOdd(), and isPrime() that return true if the value in this object is even, odd,
or prime, respectively.
✓ The static methods isEven(int), isOdd(int), and isPrime(int) that return true if the specified value is
even, odd, or prime, respectively.
✓ The static methods isEven(MyInteger), isOdd(MyInteger), and isPrime(MyInteger) that return true
if the specified value is even, odd, or prime, respectively.
✓ The methods equals(int) and equals(MyInteger) that return true if the value in this object is equal to
the specified value.
✓ A static method parseInt(char[]) that converts an array of numeric characters to an int value.
✓ A static method parseInt(String) that converts a string into an int value.

Write a Java test program that tests all methods in the class.

••• TASK 3
The String class is provided in the Java library. Provide your own Java implementation for the following methods
(name the new class MyString):

public MyString(char[] chars);


public char charAt(int index);
public int length();
public MyString substring(int begin, int end);
public MyString toLowerCase();
public boolean equals(MyString s);
public static MyString valueOf(int i);
public int compare(String s);
public MyString substring(int begin);
public MyString toUpperCase();

Write a Java test program that tests all methods in the class.
••• Sources
• Introduction to Java Programming and Data Structures, Comprehensive Version, 11 th Edition, Y. D. Liang,
Pearson, 2019.
CMPE – 211
Preliminary Work (Pre-Lab Activity)
Laboratory Experiment # 6
Textbook Material: Chapter 9 «Objects and Classes»
Chapter 10 «Object-Oriented Thinking»
Chapter 11 «Inheritance and Polymorphism»

••• TASK
Design the Java classes named Shape, Rectangle and Point by taking into account the following
UML diagram: Write a Test class to verify your implementation.

/
Shape
-color : String
-location : Point
/
+Shape(String)
+getX() : double
+getY() : double
+setLocation(double,double) : void
+getColor() : String
+setColor(String) : void
+Print() : void
/

////
//////
Circle Point
+radius : double -x : double
+setCenter(double,double) : void -y : double
+getCenter () : Point +getX() : double
+setColor (String) : void +setX() : void
+getColor() : String +getY() : double
+Print() : void +setY() : void
+Circle(double) +Print() : void

Rectangle
+width : double
+height : double
+getCornerLeftLow() : Point
+getCornerLeftUpp() : Point
+getCornerRightLow() : Point
+getCornerRightUpp() : Point
+setLocation(double,double) : void
+setColor(String) : void
+getColor() : String
+getArea() : double
+Print() : void
+Rectangle(double,double)
NOTES: (1) The location of a Rectangle object is defined as its lower left corner and the
location of a circle is defined as its center.
(2) The default color of each Rectangle and Circle object is White

••• Sources
• Introduction to Java Programming and Data Structures, Comprehensive Version, 11th Edition, Y. D. Liang,
Pearson, 2019.
CMPE – 211
Preliminary Work (Pre-Lab Activity)
Laboratory Experiment # 7
Textbook Material: Chapter 9 «Objects and Classes»
Chapter 10 «Object-Oriented Thinking»
Chapter 11 «Inheritance and Polymorphism»
Chapter 12 «Exception Handling and Text I/O»

••• TASK 1

Write, Compile and Execute a Java program that prompts the user to read two integers
and displays their sum. Your program should prompt the user to read the number again if
the input is incorrect.

You should use InputMismatchException to detect cases when input is not correct.

••• TASK 2

Write, Compile and Execute a Java program that meets the following requirements:

■ Creates an array with 100 randomly chosen integers.

■ Prompts the user to enter the index of the array, then displays the corresponding
element value. If the specified index is out of bounds, display the message Out of Bounds.

You should use ArrayIndexOutOFBoundsException to detect cases when the index is


out of bounds.

••• TASK 3

Write, Compile and Execute a Java program that creates a file named Exercise.txt and
writes 100 integers created randomly into the file using text I/O. Integers must be
separated by spaces in the file. Then, read the data back from the file and display the data
in increasing order.

••• Sources
• Introduction to Java Programming and Data Structures, Comprehensive Version, 11 th
Edition, Y. D. Liang, Pearson, 2019.

You might also like