0% found this document useful (0 votes)
8 views20 pages

BCS 210 OOP Exam Marking Guide

This document is an examination paper for the course 'Object Oriented Programming II' at Masinde Muliro University of Science and Technology for the 2018/2019 academic year. It includes instructions for candidates, a compulsory question, and several programming tasks related to object-oriented concepts such as class definitions, error identification, and program implementations. The exam covers topics such as tax computation, quadratic equations, and bank account management.
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)
8 views20 pages

BCS 210 OOP Exam Marking Guide

This document is an examination paper for the course 'Object Oriented Programming II' at Masinde Muliro University of Science and Technology for the 2018/2019 academic year. It includes instructions for candidates, a compulsory question, and several programming tasks related to object-oriented concepts such as class definitions, error identification, and program implementations. The exam covers topics such as tax computation, quadratic equations, and bank account management.
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/ 20

WURO UNIVE

S N D EM

EAND 1E
co2YDepmed
(University of Choice)
MASINDE MULIRO UNIVERSITY OF
SCIENCE AND TECHNOLOGY
(MMUST)
MAIN CAMPUS

UNIVERSITY EXAMINATIONS
2018/2019 ACADEMIC YEAR
SECOND YEAR FIRST SEMESTER EXAMINATIONS

FOR THE DEGREE


OF
BACHELOR OF SCIENCE IN (COMPUTER SCIENCE,
INFORMATION TECHNOLOGY, INFORMATION SYSTEMS AND
KNOWLEDGE MANAGEMENT) &
TECHNOLOGY EDUCATION (COMPUTER STUDIES)

cOURSE CODE: BCS 210/BIT 210

COURSE TITLE: OBJECT ORIENTED PROGRAMMING II

DATE: Tuesday 29th January, 2019 TIME: 12.00 -2.00p.m.


INSTRUCTIONS TO CANDIDATES

Question ONE (1) is compulsory


Answer THREE (3) questions
This is an OPEN Book Exam

TIME: 2 Hours

MMUST observes ZERO tolerance to examination cheating


This Paper Consists of 7 Printed Pages. Please Turn Over.
BCS 210/ BIT 210

Ouestion One(30 marks-Compulsorv)


It should store
the sales tax for a purchase.
a) Define a class named TaxWhiz that computes method,
instance variable.. This class should
have one public
the current tax rate as an the
value is price times
calcTax (double price),
which returns a double, whose
Ksh.100, the
tax rate. For example, if the tax rate is 4 percent, 0.04, and the price is [5 Marks]
calcTax () should return 4.0.
[4 Marks]
the errors in the following code:
b) Identify and fix

1 public class Test {


2 public static void main(String[] args) {
3 double[100] r5
4
5 for (inti =0; i <r.length); i++);
6 r(i) = Math.random * 100;

7 for (int i = 0; i <r.length; it+)

8 System.out.println(l )
93
103 [5 Marks]
the pattern
Write a complete Java class that displays
c)
33
555
7777
99999 assigns grades
gets the best score, and then
a program that
reads student scores,
d) Write
[6 Marks)
based on the following scheme:

Grade is A if score is>= best 10;


-
=

Grade is B if score is> best 20;


-

>= best 30;


Grade is C if score is
-
=
best 40;
Grade is D if score is>
Grade is F if otherwise

enter the total number of students, then prompts the user to


The program prompts the user to
the grades. Here is a sample run:
and concludes by displaying
enter all of the scores,

Enter the number of students: 4


Enter 4 scores: 40 55 70 58Ptm
Student 0 score is 40 and grade is B
Student 1 score is 35 and grade
is
Student 2 score is 70 and grade is A
Student 3 score is 58 and grade is B

PROGRAMMING II
BCS 210/BIT 210: OBJECT ORIENTED
BCS 210/ BIT 219

eWrite a program that displays numbers in a triangular pattern, as shown in Figure below.
The number of lines in the
display changes to fit the window as the window resizes[6 Marks]

Exergise15 3 ID

5
5 6 7
6 6 7 8
4 6 6 7 s9
23 4 5 67 8 9 10
1 2 3 4 6 6 7 8 9 1011
W i t e a program that prompts for a n integer value for radius, computes area of a circle using
a constant Pl, and displays the area computed. Use InputDialogBox for prompting the value

for the radius. [4 Marks]

Question Two (15 Marks)


a) The two roots of a quadratic equation ax +bx t e = 0 can be obtained using the

following formula:
[8 Marks]

-b + V# 4ac - V - 4ac
2a
and r= 2a

b-4ac is called the discriminant of the quadratic equation. If it is positive, the equation has
two real roots. If it is zero, the equation has one root. If it is negative, the equation has no
real roots. Write a program that prompts the user to enter values for a, b, and c and displays
the result based on the discriminant. If the discriminant is positive, display two roots. If the
discriminant is 0, display one root. Otherwise, display "The equation has no real roots".
Note you can use Math.pow(x, 0.5) to compute Here are some sample runs. [8 Marks]

BCS 210/BIT 210: OBECT ORIENTED PROGRAMMING II


3
BCS 210/ BIT"210

er

Enter a, b, c 103
Theroots are-0381966 and2.6180B

Enter a, b, e 12 0 1
The root is 1

Enter a, C 123
he equation has ng real roots

(b Consider the code below


class Shape
private Date dateCreated;
private String color;
private String name;

I/public Shape(){
public Shape (Date date, String color, String Nane)

public String getName (){ return name;}


class Rectangle extends Shape

private int length;


private int width;

public Rectangle 0

System.out.println ("This is a Rectangle");


super();
super.getName ();

i) Write the definition of the constructor in line 8 such that it initializes


instance variables with the values passed to it.
13 Marks
(i) Identify and explain error(s) in the code.
2 Marks

c) Conisder the Code below

BCS 210/BIT 210. OBJECT ORIENTED PROGRAMMING II


BCS 210/ BIT 210
Class A

final double
pi
private int radius;3.142;
=

public static double area()

Teturn pi *
radius *
radius;

private int
getRadius ()
return radius;

1 Class B extends A

public static double area()

return 3.142 getRadius () * get Radius ();


D

State and explain TWO errors in the code above. 2 Marks


Question Two (15 Marks)
a) Define the class bankAccount to store a bank customer's account number and balance.
Suppose that account number is of type int, and balance is of type double. Your class should,
at least, provide the following operations: set the account number, retrieve the account
number, retrieve the balance, deposit and withdraw money, and print
account information. Add appropriate constructors. (3 Marks)

b) Every bank offers a checking account. Derive the class checkingAccount from the class
bankAccount (designed in part (a). This class inherits members to store the account number
account typically receives
and the balance from the base class. A customer with checking
a

and pays service charges if the balance falls below


interest, maintains a minimum balance,
inherited from the base class, this class
the minimum balance. In addition to the operations
interest rate, retrieve interest rate, set minimum
should provide the following operations: set
set service charges, retrieve service charges, post
balance, retrieve minimum balance,
less than the minimum balance, write a check, withdraw
interest, verify if the balance is
account information. NB: Add
(override the method of the base class), and print
appropriate constructors.

(5 Marks)
the class savingsAccount from the class
offers savings account. Derive
c) Every bank
a

This class inherits members to store the account number


bankAccount (designed in part (a).

ORIENTED PROCRAMMING II
BCS 210/BIT 210: OBJECT
BCS 210/ BIT 210

and the balance from the base class. A customer with a savings account typically receives
nterest, makes deposits, and withdraws money. In addition to the operations inherited from
the base class, this class should provide the following operations: set interest rate, retrieve
interest rate, post interest, withdraw (override the method of the base class), and print
account information. NB: Add appropriate constructors. (4 Marks)
d) Write a program to test your classes designed in parts (6) and (©). (3 Marks)
Question Three (15 Marks)
a) Design a class named Account that contains:
i. A private int data field named id for the account (default 0).
i. A private double data field named balance for the account (default 0.
ii. A private double data field named annuallnterestRate that stores the current interest
rate (default 0). Assume all accounts have the same interest rate.
iv. A private Date data field named dateCreated that stores the date when the account
was created
Y. A no-arg constructor that
creates a default account.
V1. A constructor that creates an
vii. The accessor and mutator
account with the specified id and initial balance
methods for id, balance, and annuallnterestRate.
viii. The accessor method for dateCreated.
ix. A method named getMonthlylnterestRate) that returns the monthly interest rate.
X. A method named withdraw that withdraws a
account.
specified amount from the
xi. A method named
deposit that deposits a specified amount to the account.
Required:
Draw the UML diagram for the class. Implement the class. Write a test program that
creates an Account object with an account ID of 1122, a balance of $20,000, and an
annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500,, use the
deposit method to deposit $3,000, and print the balance, the monthly interest, and the
date when this account was created.
[12marks]
b) What is the printout of the following code? [3 Marks]
public class Foo {
private boolean x;
public static void main(String[] args) {
Foo foo new Foo0;
System.out.println(foo.x);

BCS 210/BIT 210: OBJECT ORIENTED PROGRAMMING II


6
BCS 210/ BIT 210

Question Four (15 Marks)


(8) Marks of a s t u d e ti n 10 subjects are store in an array shown in Figure a. 1o

34 56 76|12 54 754S 56 76 54]


Figure 3: Marks of a student in 10 subjects

the
are equired to write a Java program that calculates Ñ of this student using
formula

where

5 Marks)

b) Consider the definition of the class C shown below.


public class C

int m;
int n;
int nin)
public C(int mIn,

m=mIn;
n = nIn;

public int ml ()

return mtn

so that it returns the


difference
B that overrides method m1 ()
Define a subclass of C named access modifier for the instance
between m and n instead of their sum. Provide the appropriate
[5 marks]
variables m and n.

c) Given the classes with the following headers


public class Animal
DomesticAnimal extends Animal . . .

public class
extends DomesticAnimal. .

class FarmAnimal
publi
class HousePet extends DomesticAnimal. ..
public FarmAnimal
class Cow extends
. . .

public
extends FarmAnimal
public c l a s s Goat
. .

extends Cow
public class DairyCow
.

the hierarchy created by these declarations. [2 marks]


draw a class diagram representing

Given the preceding hierarchy of classes,


state with reasons why the following
d) [3 marks]
assignments are coIrect/wrong.
DairyCow dc = new FarmAnimal ();
FarmAnimal fa = new Gcat ();
Cow ci = new DomesticAnimal ();
Cow c2 = new DairyCon()
Domestichnimal dom = new HousePet ()

BCS 210/BIT 210: OBJECT ORENTED PROGRAAMMING II


QUESTION ONE: COMPULSORY QUESTION [30 MARKS]
(a) Write definition of class TaxWhiz... [5 Marks]
1 public class TaxWhiz
2 {
3 private double rate;
4

5 public double calcTax(double price)


6 {
7 return price * rate;
8 }
9 }

(b) Identify errors and fix [4 Marks]


• Line 6 using parentheses instead of subscript operator to access array ele-
ment
• Line 8 the name of the array is coming after the subscript operator
(c) Write a program to print pattern [5 Marks]
1 public class Pattern {
2 public static void main(String[] args) {
3 for(int i = 1; i < 10; i += 2)
4 {
5 for(int j = 0; j < i; j += 2)
6 {
7 System.out.print(" " + i + " ");
8 }
9 System.out.println();
10 }
11 }
12 }

NB: The student could use different approach, check student code
keenly to see if the question is logically answered

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR| Page 8
(d) Best score [6 Marks]
1 import java.util.Scanner;
2 import java.util.Arrays; // for getting best score
3 public class BestScore {
4 public static void main(String[] args) {
5 int students;
6 int[][] scores;
7 System.out.print("Enter the number of students: ");
8 Scanner s = new Scanner(System.in);
9 students = s.nextInt();
10 scores = new int[students][4];
11 System.out.print("Enter 4 scores: ");
12 String line; //read the four scores on a single line
13 Scanner ss = new Scanner(System.in);
14 line = ss.nextLine(); //read values on a single line
separated by whitespace
15 String numbers[] = line.split(" "); //create an array of
string-numbers
16 //now convert this numbers and throw them in the 2D array
17 int k = 0; //track students
18 int c = 0; //track scores
19 int[] marks;
20 marks = new int[4];
21 int t = 0;
22 for(String nums : numbers) //for each string in numbers
23 { //convert to integer
24 int num = Integer.parseInt(nums);
25 marks[t] = num; //temp holder for getting best score
26 scores[k][c] = num;
27 k++;
28 c++;
29 t++;
30 }
31 Arrays.sort(marks); //sort array in ascending order
32 //after sorting, the best score is the last value in the
array
33 int best = marks[marks.length - 1]; //grab the best score
34 c = 0; //for display, start recounting scores
35 char grade = ’F’;

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR| Page 9
36 for(int i = 0; i < scores.length; i++) //for each student
37 {
38 if( scores[i][c] >= best - 10)
39 grade = ’A’;
40 else if (scores[i][c] >= best - 20)
41 grade = ’B’;
42 else if (scores[i][c] >= best - 30)
43 grade = ’C’;
44 else if (scores[i][c] >= best - 40)
45 grade = ’D’;
46 System.out.println("Student " + i + " score is " +
scores[i][c] + " and grade is " + grade);
47 c++;
48 }
49 }
50 }

(e) Pattern [6 Marks]


1 public class Patterns {
2 public static void main(String[] args) {
3 for(int i = 1; i < 12; i++)
4 {
5 for(int j = 1; j <= i; j++)
6 {
7 System.out.print(" " + j + " ");
8 }
9 System.out.println();
10 }
11 }
12 }

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 10
(f) Area of circle using InputDialogBox [4 Marks]
1 import javax.swing.JOptionPane;
2 public class AreaCircle {
3

4 public static void main(String[] args) {


5 int radius;
6 final double PI = 3.142;
7 String rad = JOptionPane.showInputDialog(null, "Enter
Radius ");
8 radius = Integer.parseInt(rad);
9 double area = PI * radius * radius;
10 JOptionPane.showMessageDialog(null, "Radius = " + radius
+ " Area = " + area);
11 }
12 }

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 11
QUESTION TWO [15 MARKS]
(a) Quadratic roots [8 Marks]
1 import java.util.Scanner;
2 public class Quadratic {
3 public static void main(String[] args) {
4 double[] vals;
5 vals = new double[3];
6 Scanner s = new Scanner(System.in);
7 System.out.print("Enter a, b, c : ");
8 String line = s.nextLine(); //read the three inputs on
single line
9 //split the inputs and convert each to double
10 String[] inputs = line.split(" ");
11 for(int i = 0; i < 3; i++)
12 {
13 double num = Double.parseDouble(inputs[i]);
14 vals[i] = num;
15 }
16 //calculate the discriminant
17 double delta = (vals[1] * vals[1]) - (4 * vals[0] * vals
[2]);
18 double r1 = (-vals[1] + Math.pow(delta, 0.5))/(2 * vals
[0]);
19 double r2 = (-vals[1] - Math.pow(delta, 0.5))/(2 * vals
[0]);
20 if(delta == 0)
21 {
22 System.out.println("The root is " + r1);
23 }
24 else if(delta > 0)
25 {
26 System.out.println("The roots are " + r1 + " and " +
r2);
27 }
28 else
29 System.out.println("The equation has no real roots");
30 }
31 }

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 12
(b) (i) Writing definition of Constructor at line 8 [3 Marks]
1 public Shape(Date date, String color, String Name)
2 {
3 dateCreated = date;
4 this.color = color;
5 name = Name;
6 }

(ii) Errors in the code [2 Marks]


• Line 21 : Call to super should be first line in the constructor
• Line 21 : Calling a super constructor that has not been defined
(c) Errors in the code [2 Marks]
• Line 17 : You cannot override a static method
• Line 19 : You cannot access a private method from outside the class

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 13
QUESTION THREE [15 MARKS]
(a) BankAccount class [3 Marks]
1 class BankAccount {
2 private int accountNo;
3 private double balance;
4

5 public BankAccount(){
6

7 }
8 public BankAccount(int no, double bal){
9 accountNo = no;
10 balance = bal;
11 }
12 public void setAcNumber(int n)
13 {
14 accountNo = n;
15 }
16 public void setBalance(double b)
17 {
18 balance = b;
19 }
20 public int getAcNumber(){
21 return accountNo;
22 }
23 public double getBalance(){
24 return balance;
25 }
26 public void withdraw(double amount){
27 balance = balance - amount;
28 }
29 public void deposit(double amount){
30 balance = balance + amount;
31 }
32 public void display(){
33 System.out.print("Account Number = " + getAcNumber() +
34 "\nBalance = " + getBalance());
35 }
36 }

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 14
(b) Checking Account [5 Marks]
1 class CheckingAccount extends BankAccount {
2 private double interestRate;
3 private double minBalance;
4 private double serviceCharges;
5

6 public void setInterestRate(double r){


7 interestRate = r;
8 }
9 public void setMinBalance(double min){
10 minBalance = min;
11 }
12 public double getMinBalance(){
13 return minBalance;
14 }
15 public double getInterestRate(){
16 return interestRate;
17 }
18 public void setServiceCharge(double c){
19 serviceCharges = c;
20 }
21 public double PostInterest()
22 {
23 return getBalance() * getInterestRate();
24 }
25 public boolean verifyMinBal()
26 {
27 return getBalance() < minBalance;
28 }
29 public void payServiceCharge(){
30 if(verifyMinBal())
31 setBalance(getBalance() - serviceCharges);
32 }
33 }

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 15
(c) Savings Account [4 Marks]
1 class SavingsAccount extends BankAccount {
2 private double rate;
3

4 public SavingsAccount(){
5 }
6 public void setRate(double r){
7 rate = r;
8 }
9 public double getRate(){
10 return rate;
11 }
12 public double postInterest(){
13 return rate * getBalance();
14 }
15 @Override
16 public void withdraw(double amount){
17 setBalance(getBalance() - amount);
18 }
19 @Override
20 public void display(){
21 System.out.print("Account Number = " + getAcNumber() +
22 "\nBalance = " + getBalance() +
23 "\nInterest Rate = " + getRate());
24 }
25 }

(d) Program to test classes in (b) and (c) [3 Marks]


1 public class BankAccountTest {
2 public static void main(String[] args) {
3 CheckingAccount ca = new CheckingAccount();
4 SavingsAccount sa = new SavingsAccount();
5 //Check for appropriate function calls in the student
code
6 }
7 }

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 16
QUESTION FOUR [15 MARKS]
(a) Draw UML. Implement the class. Write test program [12 Marks]
Account
int id
double balance
double annualInterestRate
Date dateCreated
Account()
Account(int, double)
setID(int):void
setBalance(double):void
setInterest(double):void
getID(): int
getBalance(): double
getInterest(): double
getDateCreated(): String/Date
getMonthlyInterestRate(): double
withdraw(double): void
deposit(double): void

Drawing UML – Award 4 Marks

Implementation of the class — Award 5 Marks


1 import java.util.Date;
2 class Account
3 {
4 private int id = 0;
5 private double balance = 0;
6 private double annualInterestRate = 0;
7 Date dateCreated = new Date();
8

9 public Account() {
10

11 }
12 public Account(int id, double bal){
13 this.id = id;
14 balance = bal;
15 }
16 public void setID(int i) {
17 id = i;
18 }
19 public void setBalance(double b){

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 17
20 balance = b;
21 }
22 public void setInterest(double r) {
23 annualInterestRate = r;
24 }
25 public int getID(){
26 return id;
27 }
28 public double getBalance(){
29 return balance;
30 }public double getInterest(){
31 return annualInterestRate;
32 }
33 public String getDateCreated(){
34 return dateCreated.toString();
35 }
36 public double getMonthlyInterestRate(){
37 return annualInterestRate / 12;
38 }
39 public void withdraw(double amount){
40 balance = balance - amount;
41 }
42 public void deposit(double amount){
43 balance = balance + amount;
44 }
45 }

Test class - Award 3 Marks


1 public class AccountTest {
2 public static void main(String[] args) {
3 Account ac = new Account();
4 ac.setID(1122);
5 ac.setBalance(20000);
6 ac.setInterest(0.045);
7 ac.withdraw(2500);
8 ac.deposit(3000);
9 System.out.println("Balance = " + ac.getBalance());
10 System.out.println("Monthly Interest = " + ac.
getMonthlyInterestRate());

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 18
11 System.out.println("Date Created = " + ac.getDateCreated
());
12 }
13 }

(b) What will be the output of the code [3 Marks]


false
QUESTION FIVE [15 MARKS]
(a) Standard deviation calculation [5 Marks]
1 public class StandardDeviation {
2 public static void main(String[] args) {
3 int data [] = {34, 56, 76, 12, 54, 75, 48, 56, 78, 54};
4 double sum = 0.0;
5 for(int i : data){ //calculate sum of all elements
6 sum += i;
7 }
8 double mean = sum / data.length; //get the mean
9 System.out.println("Sum = " + sum);
10 double x_minus_mean[] = new double [10]; //store square
of x - mean
11 int i = 0;
12 for(int x : data)
13 {
14 x_minus_mean[i] = (x - mean) * (x - mean);
15 i++;
16 }
17 double sum_x_minus_mean = 0;
18 for(double d : x_minus_mean)
19 {
20 sum_x_minus_mean += d;
21 }
22 double std = Math.sqrt((sum_x_minus_mean)/ (data.length -
1));
23 System.out.println("Mean = " + mean);
24 System.out.println("STD = " + std);
25 }
26 }

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 19
(b) Subclass of C named B [5 Marks]
1 public class B extends C {
2 public int m1() {
3 return m - n;
4 }
5 }
6 //Since m and n have default access modifier, they can
7 //accessed from within the same package assuming the
8 //two classes are in the same package. If the two
9 //classes are not in the same package, then m and n
10 //should either have protected or public access modifiers

(c) Draw class diagram [2 Marks]

(d) Why following assignments are correct/wrong [3 Marks]


• DairyCow dc = new FarmAnimal(); - Wrong. A FarmAnimal is not
necessarily a DairyCow. This implicit casting of supertype to subtype is
not allowed, unless its done explicitly by the programmer as
DairyCow dc = (DairyCow)new FarmAnimal();
• FarmAnimal fa = new Goat(); - Correct. A Goat is an instance of a
FarmAnimal since FarmAnimal is a supertype of a Goat
• Cow c1 = new DomesticAnimal(); - Wrong. DomesticAnimal is not
necessarily a Cow. This implicit casting of supertype to subtype is not
allowed, unless its done explicitly by the programmer as
Cow c1 = (Cow)new DomesticAnimal();
• Cow c2 = new DairyCow(); - Correct. A DairyCow is a Cow
• DomesticAnimal dom = new HousePet(); - Correct. A HousePet is
a DomesticAnimal

|BCS 210 Object Oriented Programming, SCI, MMUST 2018. Main Examination. Dr. AR|Page 20

You might also like