Exercise 02
Exercise 02
SEMESTER/SESSION : 2 (2021/2022)
DURATION :3 HOURS
_____________________________________________________________________________
QUESTION 1
i) result = x + y; (1 mark)
c) Explain the term logic error. Identify and correct any logic errors in the
following Java program in Figure 1.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter score for DCT1094 ");
int score = input.nextInt();
if (score >=40)
System.out.println("Fails");
}
}
(6 marks)
Figure 1- Java Program Containing Logic Errors
d) Write a Java program to input a thousand (1000) integers and print the (11 marks)
average. Do not use an array.
2
_____________________________________________________________________________
QUESTION 2
ii)
public static void average(int N1, int N2) {
return ((N1+N2)/2.0);
}
(3 marks)
QUESTION 3
Write a Java program that prompts the user to input the length and width of a
rectangle. The program should then display the area of the rectangle.
The calculation of the area is done in a method called getArea that takes
two integers (length and width) as parameters and returns the area of the
rectangle (area = length x width).
3
_____________________________________________________________________________
QUESTION 4
The following Java program (Figure 3) is designed to calculate the perimeter
for a rectangle and a cuboid. Please answer the following questions based on
the provided code.
rectangle(){
width=1;
length=1;
}
cuboid(){
width=3;
length=2;
height=5;
}
4
_____________________________________________________________________________
a) Identify and list TWO (2) classes, other than the main class, that are
defined in the program.
(2 marks)
b) Identify and list all objects instantiated in the program.
(2 marks)
c) Identify the parent class and its corresponding child class in the
program. (2 marks)
d) Create a UML Class Diagram to illustrate the classes in the program. (6 marks)
5
_____________________________________________________________________________
QUESTION 5
ii) A no-arg constructor that creates a default Pyramid. Set the default (3 marks)
values 5 for width, length and height.
iii) A constructor that creates a Pyramid with the specified width, (3 marks)
height, and length.
iv) A method named getVolume() that returns the area of this (3 marks)
Pyramid.
Volume =(width * length * height)/3;
vi) A appropriate accessor and mutator methods for the class. (6 marks)
b) Write a test program that instantiates (create) TWO (2) Pyramid objects
namely pyramid1 and pyramid2 to hold the following data. (9 marks)
-------------------------------------------End of question----------------------------------------
6