CBOP3203 Object Oriented Programming

tugasan ini telah dibuat pada semester september 2008 dan telah dihantar oleh penulis kepada tutor. harap gunakan ia sebagai rujukan dan panduan dan bukan utk ditiru/plagiat.tq

Question 1


import java.util.*;

import java.io.*;

class Loan2 {

public static void main(String[] args) throws IOException {


// Constant for the number of months in a year

private final int MONTHS_IN_YEAR = 12;

// The amount of the loan

private double loanAmount;

//The monthly interest rate

private double monthlyInterestRate;

// The number of monthly payments

private int numberOfPayments;

// Constructor

public Loan2(double amount, double rate, int period)



setRate (rate );



//Returns the loan amount.

public double getAmount( )


return loanAmount;


//Returns the loan period in the number of years.

public int getPeriod( )


return numberOfPayments / MONTHS_IN_YEAR;


//Returns the annual interest rate.

public double getRate( )


return monthlyInterestRate * 100.0 * MONTHS_IN_YEAR;


//Returns the monthly payment

public double getMonthlyPayment( )


double monthlyPayment;

monthlyPayment = (loanAmount * monthlyInterestRate)/(1 – Math.pow(1/(1 + monthlyInterestRate),numberOfPayments ) );

return monthlyPayment;


//Returns the total payment

public double getTotalPayment( )


double totalPayment;

totalPayment = getMonthlyPayment( ) * numberOfPayments;

return totalPayment;


//Sets the loan amount of this loan.

public void setAmount(double amount)


loanAmount = amount;


//Sets the interest rate of this loan.

public void setRate(double annualRate)


monthlyInterestRate = annualRate / 100.0 / MONTHS_IN_YEAR;


//Sets the loan period of this loan.

public void setPeriod(int periodInYears)


numberOfPayments = periodInYears * MONTHS_IN_YEAR;


Question 1 B

Java Coding

import java.util.*;

import java.io.*;

public class gas2


public static void main(String[] args) throws IOException


// to set the variable attribute

int pollutant_no;

float miles;

float odometer;

Pembaca read;

read = new Pembaca();

// to prompt selection menu


System.out.println (“1. Carbon monoxide”);

System.out.println (“2. Hydrocarbons”);

System.out.println (“3. Nitrogen oxides”);

System.out.println (“4. Nonmethane hydrocarbons”);

//to get input from user

System.out.print (“\nEnter pollutant number: “);

pollutant_no=read.bacaInt ();

//to get input from user

System.out.print (“\nEnter number of grams emitted per mile: “);

miles=read.bacaFloat ();

//to get input from user

System.out.print (“\nEnter odometer reading (round up to greater number-(in miles): “);

odometer=read.bacaFloat ();

// to check the value given by the user

if (pollutant_no == 1 && odometer <= 50000)

System.out.println (“\nEmission exceed permitted level of 3.4grams/mile”);

else if (pollutant_no == 1 && odometer >= 50000)

System.out.println (“\nEmission exceed permitted level of 4.2grams/mile”);

else if (pollutant_no == 2 && odometer <= 50000)

System.out.println (“\nEmission exceed permitted level of 0.31grams/mile”);

else if (pollutant_no == 2 && odometer >= 50000)

System.out.println (“\nEmission exceed permitted level of 0.39grams/mile”);

else if (pollutant_no == 3 && odometer <= 50000)

System.out.println (“\nEmission exceed permitted level of 0.4grams/mile”);

else if (pollutant_no == 3 && odometer >= 50000)

System.out.println (“\nEmission exceed permitted level of 0.5grams/mile”);

else if (pollutant_no == 4 && odometer <= 50000)

System.out.println (“\nEmission exceed permitted level of 0.25grams/mile”);

else if (pollutant_no == 4 && odometer >= 50000)

System.out.println (“\nEmission exceed permitted level of 0.31grams/mile”);




Print screen

Question 2 A


import javax.swing.*;

class Gamehilo{

//to set maximum try

private final int MAX_NO = 6;

//to set smallest secret number

private final int NO_PALING_KECIL = 1;

// to set biggest secret number

private final int NO_PALING_BESAR= 100;

//computer generated number

private int nomborRahsia;

// constructor – constructor name must be the same with class name

public Gamehilo( ) {


// main method

public static void main (String[] args) {

Gamehilo hiLo = new Gamehilo( );



// to call other private method

public void start ( ) {

int answer;


answer = prompt(“Anda ingin bermain Permainan Hi-Lo?”);

while (answer == JOptionPane.YES_OPTION) {

generatenomborRahsia( );


answer = prompt(“Nak Main Lagi??”);



private void describeRules( ) {

System.out.println(“Inside describeRules”);


// to generate random number from 1 to 100

private void generatenomborRahsia( ) {

double X = Math.random();

nomborRahsia = (int) Math.floor(X*100) + 1;

System.out.println(“Secret Number: ” + nomborRahsia);


// to get the next guess number from user

private int getNextGuess( ) {

String inputStr;

int input;

while (true) {

inputStr = JOptionPane.showInputDialog(null,”Next Guess”);

input = Integer.parseInt(inputStr);

if (NO_PALING_KECIL <= input && input <= NO_PALING_BESAR) {

return input;


// error message for wrong input from user

JOptionPane.showMessageDialog(null, “Input Salah: ” +

“Nombor mesti ” + NO_PALING_KECIL +

“dan ” + NO_PALING_BESAR);



// play the game

private void playGame( ) {

int guessCount = 0;

int guess;

do {

guess = getNextGuess();


// check the guessed number

if (guess < nomborRahsia) {

JOptionPane.showMessageDialog(null, “Tekaan anda rendah”);

} else if (guess > nomborRahsia) {

JOptionPane.showMessageDialog(null, “Tekaan anda tinggi”);


} while ( guessCount < MAX_NO &&

guess != nomborRahsia );

// output appropriate message

if ( guess == nomborRahsia ) {

JOptionPane.showMessageDialog(null, “Anda Berjaya Di Dalam “

+ guessCount + ” percubaan.Terima Kasih”);

} else {

JOptionPane.showMessageDialog(null, “Anda Salah. Nombor sebenar ialah “

+ nomborRahsia);



//prompt yes-no menu

private int prompt(String question) {

int reply;

reply = JOptionPane.showConfirmDialog(null,




return reply;


Question 2B

During developing the java code for the games, several problems were encountered. Some of these problems and difficulties were because the codes need to be well organized and structured in order to ensure that the program can be run by the user.

Some of the problems are:

1. To generate random numbers as the nomborRahsia

– I found this difficulty as the secret number need to set randomly by the computer. However, based on some examples given in few website, to generate random number some of these program used math.random operation. Therefore, to generate random number this math.random operation need to be used. However, the program written need to used javax.swing coding to enable math.random operation. This nomborRahsia is the correct number if the user can guess it right.

2. To determine which file library to be used

– Since the program using some simple GUI to interact with user, at the earlier stage of writing the program, I’ve used the java.io library. However, by using the java.io library my program failed to compile and execute. The error was “cannot find symbol variable JOptionPane”. However, this problem was solved by using the javax.swing library. The javax.swing library enables the GUI to be used in the java program.

3. To decide whether to use text based application or frame java programs

– The other problem I faced while developing the program was in deciding whether to use the text based application of frame java program. The text based application approach will give the output similar to the question 1(b) screen where the screen will be similar to command prompt screen. The hilo game program however need the user to interact easily with the program. I’ve decided to have a simple pop-up dialog box that will enable user to interact with the program.

It is quite difficult to know what method need to be used in order to have a simple pop-up dialog box for user to key in the inputs. I’ve been searching in the internet to find out what method to use. Most of the coding found was using the JOptionPane method to allow simple pop up dialog box to interact with the user. So in this program, I’ve opted to use the JoptionPane in order to allow the use of pop-up dialog box interaction with the user.

4. Writing coding in JOptionPane

– Since I’ve decided to use the JOptionPane for this program in order to have pop-up dialog box and it was never been used before, the other problem that I faced was to write the coding using the JOptionPane class. Some simple coding was initially failed to compile. This problem happened to almost coding that I am using the JOptionPane. The most difficult problem was to make the “Anda ingin bermain Permainan Hi-Lo? pop-up window. Initially the pop-up windon Yes button was not functioning.

I managed to make the button function works by taking some example in the internet with similar purpose of menu pop-up menu functions.

5. To replace Yes and No with Ya atau Tidak

– I’ve been trying to change the pop-up window feature for selection of answer Yes or No to Bahasa Melayu Ya atau Tidak. However, I still couldn’t change it to Bahasa Melayu. I’ve searched in the internet, the feature actually cannot be change to any language since I used JOptionPane.YES_OPTION.


  1. Dato’ Dr. Zaiton Osman et. al. (2004). Open University Malaysia: Learning Skills for Open Distance Learners. Kuala Lumpur. Utusan Publications and Distributors Sdn. Bhd

  1. Barry Burd. (2007). Java for Dummies 4th Edition. New Jersey. Wiley Publishing Inc.

  1. Stuart Reges & Marty Stepp. (2008). Building Java Programs – A Back to Basics Approach. Boston. Pearson Education Inc.

  1. http://www.javabeginner.com

  1. Kathryn E. Sanders & Andries van Dam (2006). Object-Oriented Programming in Java-A Graphical Approach. Boston. Pearson Education Inc.

  1. Rogers Cadenhead. (2000). Sams: Teach Yourself Java 2 in 24 hours Indiana. Sam Publishing.

1 Comment

Filed under Uncategorized

One response to “CBOP3203 Object Oriented Programming

  1. mastura

    salam sejahtera…

    bole tak bagitahu saya di mn nk dpt kan note slide utk cbop3203 ni… biasa nye slide show sama je ngan note dlm module…tp diterjemahkan dalam bahasa melayu la

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s