Escolar Documentos
Profissional Documentos
Cultura Documentos
XS MAPHUMULO
***Java guide***
1|Page
2|Page
The Author
Acknowledgements
I would like to express my greatest gratitude to my high school teachers MN
Ngwane and KC Ngcobo (IT educators), for giving me the best and pure
programming skills in java. Also a special thanks to the sole editor,
Khang Mokoena.
3|Page
CONTENT
The content is structured according to the order of questions in the
final exam paper.
Section A General Programming skills
String class methods: format, split, substring, char At and Exceptions and
string handling
Writing complex mathematical formulas using arithmetic operators and
Math class methods: random, round, power etc.
Associate different (not restricted to default) events to GUI components.
Using Programming techniques for problem solving, such as loops, date
functions and casting.
Section B -OOP
Object Oriented Programming(OOP) and Advanced OOP
1. Applying objects ,methods and classes
2. Inheritance ,Encapsulation and Polymorphism
Solutions
Appendix A Naming conventions, data types, Access modifiers and escape
characters
4|Page
SECTION A
Composed of question 1!
General programming skills
5|Page
Introduction
The String classes and handling
Java Class Library (JCL) includes a huge library of codes and predefined classes of
which, we as developers use in order to solve problems. This Library (JCL) also
contains string classes and methods such as format,split,substring ,char At and
some defensive programming statements that are used to handle string and
prevent runtime errors.
Since this is just a guide, I will not explain in detail about JCL classes but will explain
those that I will use in my source code. For those who want to dig further browse
the link: https://en.wikipedia.org/wiki/Java_Class_Library
Use the link below to download solutions to all the questions included
in this guide, however they are provided at the end of the book.
http://www.datafilehost.com/d/1dfe90c8
6|Page
7|Page
Math classes
In computational problems these classes come in handy. The table below shows
the commonly used methods. There are many more than these ones provided but
some of them are beyond the scope of your curriculum.
Method
Description
Example
abs(x)
Absolute value of x
exp(a)
Gives ea
max(x,y)
pow(a,b)
Largest of arguments x
and y
Smallest of arguments ,x
and y
Gives ab
round(x)
Nearest integer to x
sqrt(x)
Square root of x
min(x,y)
Reference
1) Marietjie Havenga & Christina Moraal,
(2007),Creative programming in java part 2 ,BitaByte
PTY (ltd)
8|Page
The following statements are used when making a decision and also in
defensive programming which is covered in section C.
If-else statement
If-else statement is the crucial tool used for validation and error
checking.
Code segment
If (Boolean condition)
{
Body of the program if the Boolean condition is true
}
else
{
Body of the program if the Boolean condition is false
}
9|Page
Equal to
Not equal to
Greater than or equal to
Smaller than or equal to
&&
||
^
!
AND
OR
XOR
NOT
10 | P a g e
LetStart(With Xolani);
if(result.LeftBehind()==true)
{
string promise = I will pick you up ;
this.GoTogetherAgain(I.promise);
}
11 | P a g e
1. Consider the above screen print. Cisco is looking for the best junior programmer from the two
universities: University of KwaZulu-Natal and University of the Free State. You are required to develop a
software that will allow each applicant to register.
Instructions
The age of the student must be in this range: 18 21, display an error message if
it beyond or less.
Ensure that the student only select one university
The date of birth must be in the form dd/mm/yyyy and use it to calculate the
age
For User Profile button (btnUserProfile) display a name tag in the text Area.
The name tag must be as follows
Surname Initial (age)
Gender
University
The button new user must clear all the fields including the text area
The button Generate Code, must append a three a character to the text area
a. Character 1 must be the first letter of the name (initial)
b. Character 2 must be any random number less than 10
c. Character 3 must be the last character of the surname
12 | P a g e
Example: Nicklaus Jobs, who was born in 1995 and studies at the University of the Free State.
Solution
Its a good programming practice to instantiate variables or data fields at a higher level
(below the class name), that you will use in different scopes of the class. From the
question, you could see that there are some variables that we will use on both scopes
(button User profile and button Generate code) and those variables must be declared as
global variables of the class.
13 | P a g e
sName = txfName.getText();
sSurname = txfSurname.getText();
sDate = txfDateofBirth.getText();
String sGender = (String)cmbGender.getSelectedItem();
cInitial = sName.charAt(0);
String date = sDate.substring(6);
int Age =2015- Integer.parseInt(date);
String sNameTag = " ";
String university= " ";
if(Age>=18 && Age<=21)
{
if(radbtnUKZN.isSelected() && radbtnUFS.isSelected())
{
JOptionPane.showMessageDialog(null," Please select only 1 university");
}
else
{
if( radbtnUKZN.isSelected() )
{
university = "University of Kwa-Zulu Natal";
}
else if( radbtnUFS.isSelected() )
{
university= "University of the Free state";
}
else
{
JOptionPane.showMessageDialog(null," Select at least one university");
}
30.
sNameTag+=sSurname +" "+cInitial+" ("+Age+")"+"\n"+sGender+"\n"+ university+"\n";
31.
txtAreaOutput.setText(sNameTag.toUpperCase());
32.
}
33. }
34. else
35. {
36.
JOptionPane.showMessageDialog(null," Incorrect age");
37.
}
Copyright2015 X.S. Maphumulo
14 | P a g e
Explanation
Line 1-3 ,declare and assign the variables using the corresponding values from the
text fields
Line 4 , the selectedItem() method of a combobox , checks the selected item then
it returns it as an object that can either be a string , integer , a real
number(double) or a character. We therefore have to explicitly type cast the
object to string type: (String) cmbgender.getSelectedItem ().a numerical example
showing type casting
double dNumber=13.5;
int iNumber = (int) dNumber;
Now iNumber will be 13
Line 5, we use the charAt (int index) method to get the first letter of the name
which is assigned to cInitial .Note cInitial was declared at the top of the class.
Nicklaus
0123456
Therefore charAt (0) will return N as a character.
Line 6, the method substring have two different signatures and that is called
method overloading. The first one uses two parameters and in this current
exercise we would have used it as follows:
String date=sDate. Substring (6, 4); where 6 is the begin index and 4 it length
Which means the compiler will start from character six to extract and take only 4
characters ahead the 6th one.
On the other hand, String = sDate.substring (6); tells the compiler to substring
starting from 6 to the rest of the word.
Line 7, In order to calculate the age, we must firstly convert the year of birth to an
integer then take 2015 minus the year converted.
Line 8-9,I have declared to variables : sNameTag (to display name tag ) and
university (to get the selected university from radio buttons)
Line 10, Validation : checks if the age is greater than 18 AND (&&) less than 21
Line 12,This is called a nested if-else statement(have an else-statement nested to
another) .Basically, we now check if the user selected the both of the radio buttons
if its true use dialog to display the error message if not continue to check .
15 | P a g e
Line 17-28, we check which university is selected then overwrite the value of the
variable university, if the user did not select any of the two display an error
message on line 28.
Line 29, if all the conditions are true: the user selected only one university then we
concatenate the variables required for a name tag. NOTE the escape characters
are used just to format the name tag. \n next line and \t tab or spaces
Check in appendix A for all escape characters.
Line 31, we display sNametag which holds the name tag, we used the method
toUppercase () just to display sNametag in capital letters.
Line 36, Look at the code again you will note that we nested everything inside the
validation of the age. In line 34 the else-statement states that if the age is not
between 18-21 then display an error message in line 36.
txfSurname.setText("");
txfName.setText("");
txfDateofBirth.setText("");
txtAreaOutput.setText("");
Explanation
private void btnNewUserActionPerformed(java.awt.event.ActionEvent evt) {
Line 1-3, We clear the text fields by overwriting their text values to an empty string
Line 4, text areas and fields uses the same properties and methods hence the text
area in internet programming is called a multiline text field.
Line 5, display a dialog indicating that all text fields are cleared.
//button - [Exit]
private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {
1. System.exit(0);
Exit the program, for enrichment: There is a class called System, it one of the
most powerful classes in java. You can use the intellisense to explore more of it
functions
16 | P a g e
Explanation
Line 1, We are required to take the last character of the surname to formulate
the code
Lets visits arrays. Since arrays are zero-based (starts from zero) then every set
of length N the last term will be N-1.
X
We could see that the actual length of the wordxolani is 6 but according to
arrays its 5 then if we let the Length to be n the last element will be n-1
Line 2, we have a Math.random () method which is used to get a random
number, but this method returns a double so we must type cast it to an integer.
NOTE in order to determine the maximum number of the random number you
must multiply with it hence here we multiplied by 10 because we want the
random number from 0 -10.
Line 3-4, we construct the code. Note we used the method String.valueOf () to
convert the random number to a string type. If this conversion was left out, the
three characters would return a sum not the consented string
2. You are developing an electronic voucher validator for a software company. The
application must check if the voucher is valid then add the name of the customer
to the combo box. The user must be able to delete the customer by selecting the
name then delete it.
Instructions
Voucher is validated as follows
I. The length of the voucher must 5 characters
II. The first character must be an integer
III. The last four characters must be letters
Copyright2015 X.S. Maphumulo
17 | P a g e
Ensure that you display a message showing that the user was
successfully deleted.
The button add must only add the user if the voucher is valid
Solution
//button Add private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
1. String sVoucher = txfVoucher.getText();
2. if(sVoucher.length()==5)
3. if(Character.isDigit(sVoucher.charAt(0)))
4.
if(Character.isLetter(sVoucher.charAt(1)))
5.
if((Character.isLowerCase(sVoucher.charAt(2)) &&
(Character.isLowerCase(sVoucher.charAt(3))&&Character.isLowerCase(sVoucher.charAt(4)))))
6.
cmbCustomers.addItem(txfNameSurname.getText());
7. }
Explanation
In programming everything builds on top of each other, therefore I will not explain
some of things I did on the previous exercise. Fasten your seatbelts it's going to be
a bumpy ride.
Line 2, we check whether the length is equivalent to five characters if not the
execution does not continue until the length is five.
Line 3, Assuming that length was five, we now check whether the first character of
the voucher is a digit. The Character class uses a lot of static methods to validate
characters .The best way to know which method to use, just type Character
Copyright2015 X.S. Maphumulo
18 | P a g e
followed by a dot the intelliSpaense will give you options and since they are selfexplanatory, it will be easy to pick the appropriate one.
Line 5, checks the last 3 characters whether they are letters or not.
Please know how to nest if-else statements and also know how to write
compound if-else statements.
Line 6, finally we now add the name to the combo box, the combo box uses a
method addItem (), which adds any object to the combo box.
//button [Delete]
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
1. if(JOptionPane.showConfirmDialog(null, "Are you sure?")== 0)
2. {
3.
cmbCustomers.removeItem(cmbCustomers.getSelectedItem());
4.
JOptionPane.showMessageDialog(null, " deleted");
5. }
6. else
7. {
8.
JOptionPane.showMessageDialog(null, " You did not delete");}
Explanation
Deleting, clearing, disposing and closing are damaging operations so before we
execute them, we need to confirm from the user.
Line 1, we confirm from the user, using the confirm dialog.
The dialog consist of three buttons, if the user clicks a yes it returns a zero
Hence my if-else statement checks if it zero then delete the name and surname.
If the user clicks no from the confirm dialog, line 8 will be executed.
19 | P a g e
3. Consider the screen print above, you are responsible for electronic investments
that are made by clients to your Bank. Develop a software that will allow a user to
make an investment. You will output a report showing the results of the simple
interest and compound interest, accumulated amounts. You have to append the
users details below the two amounts.
Your report must be as follows:
Accumulated amount in Simple interest : <amount>
Accumulated amount in Compound interest : <amount>
Date of birth : < date of birth>
Surname and Initial : <surname initial>
Gender: <gender>
20 | P a g e
Instructions to follow
The label display percentage must constantly display the percentage when the
use slides the knob of the slider.
Use the ID number to output date of birth e.g. 26 March 1998
Hint
The first 6 digits indicate the date of birth in this form YYMMDD
Use the ID number to output the gender ,
Hint
The four digits in position 7 to 10 of an identity number (ID number) indicate a
person's gender. The following applies:
>=5000: Male
< 5000: Female
Calculate and display both simple and compound interest amounts using the same
data.
Use a Dialog to output your report and must be capitalize.
Example: Emily Swift with an ID 9803260431083 and input the following data for
the investment
Amount to Invest: 12000
Years: 2
Interest: 20%
21 | P a g e
The following screen print shows the output of the above entered data.
Solution
//button [ Report]
private void btnReportActionPerformed(java.awt.event.ActionEvent evt) {
1. double dAmountInvest = Double.parseDouble(txfAmountInvested.getText());
2. int iYears =(int) SpinnerYears.getValue();
3. double dPercentage = (SliderInterest.getValue()*1.0)/100;
4. String sNameSurname = txfNameSurname.getText();
5. String ID = txfIDNumber.getText();
6. String sSurname =sNameSurname.substring(sNameSurname.indexOf(' ')+1);
7. char cInitial = sNameSurname.charAt(0);
8. String sGender=" ";
9. int iGender = Integer.parseInt(ID.substring(6,10));
10. if(iGender>=500)
11. {
12. sGender= "Male";
13. }
14. else
15. {
16. sGender = "Female";
17. }
18. String sDateOfBirth = " ";
19. if(ID.length()==13)
20. {
21. String idn = ID.substring(0,6);
22. String day = idn.substring(4,6);
23. String year = "19"+ idn.substring(0,2);
24. int month = Integer.parseInt(idn.substring(2,4));
25. String sMonth= " ";
22 | P a g e
Explanation
Line 1, instantiates the variable for the amount to be invested.
Line 2, creates a new variable year that will hold the value of the spinner.
The getValue () method of a jSpinner returns an object so we must type cast (int)
the object to an integer.
Line 3, interest can be a double or an integer but I used a double because a double
type can hold an int value but an integer (int) cannot hold a value with a decimal
(double).
23 | P a g e
SliderInterest.getValue()*1.0;
The above code is extracted from line 3. I multiplied by 1.0 to make the whole
expression a double, so that I will be able to divide by 100 then get the actual
percentage. For instance, the user may slide the knob and select 20 then to get the
actual percentage you will have to divide 20 by 100 then get 0.2 of which is a double.
If the factor 1.0 was omitted a logic error would occur because an integer divide by
an integer returns an integer.
Example
double y =10/9;
The value of y is 1.0
But
double y = (10 * 1.0)/9;
The value for y is 1.111112
Line 4, gets the name and the surname of the client. There must be a
single space between the name and the surname.
Line 5, gets the Id from the text fields as a string
Line 6, I substring or extract the surname from the sNameSurname
which contains both name and surname separated by a single space.
The indexOf() method get the first occurrence of the single space of
which occurs between the name and the surname. indexOf( )+1 simply
means move 1 step after finding a space then start to substring the rest
of the text of which is now a surname. Follow me here
Xolani Maphumulo
There is a single white space between the i and the M.The method
simply tells the compiler to add 1 after that single space and when we
add one we Jump to the M of the surname,then from M we substring
or extract everything that follows M of which is Maphumulo.
Line 7, we use the same variable sNameSurname to get the first letter
of the name. Since we start by a name so charAt(0) will return the first
letter of the name.
Copyright2015 X.S. Maphumulo
24 | P a g e
Line 8, A good programmer declare and assign a variable with an empty string if
he/she knows that the variable will need to be overwritten in different conditions.
I assigned sGender with an empty because if iGender is greater than 5000 then
sGender must be a Male else a female.
Line 10 17, we overwrite the value of sGender according to the value of iGender.
Line 19, checks whether the ID contains 13 characters.
Line 21, returns the first six characters of the date of birth from the ID.The
characters are in the form YYMMDD.
Line 22, extracts the day from idn.
Line 23, we get the year of birth. Note the question states that we must assume
that everyone was from 1900 and an ID only contains two characters of the year so
we will prefix 19 to the year of birth from the ID.
Line 25-27, since we are required to display the month in words, so I used switch
statement to determine which month at a certain case.
The if-else statement may also be used.
Line 28, Concatenate all variable required for the date of birth.
Line 30, calculate the accumulated amount for the simple interest. It is still
acceptable to have many variables for calculating the accumulated value, in fact it
very good compared to what I did.
Line 31, I want you to pay attention on the Math.pow() method since the number
of years must be an exponent so we must write it as the second parameter of the
method.
Line 33-36, the variable sOutput is used to display the report using a dialog.
Everything can be done in one line but I decided to keep on appending for the sake
of readability.
Line 37, display the report stored in sOutput.
25 | P a g e
//Slider -[ Interest ]
private void SliderInterestStateChanged(javax.swing.event.ChangeEvent evt) {
1. lblSlider.setText(String.valueOf(SliderInterest.getValue()));
Explanation
Line 1, In order to constantly display the changing value of the slider, the
stateChanged() event handler of the slide will keep track of every value the knob
changes to.
26 | P a g e
27 | P a g e
28 | P a g e
29 | P a g e
30 | P a g e
31 | P a g e
32 | P a g e
By reading the whole question surely you have noticed that we must have a
global variable kilometres that will be available to all the scopes of the class.
The below screen capture shows the instantiation of this global variable.
Explanation
Line 1, we get the departure from the combo box as a string. Since the
getSelectedItem() method of the combo box returns an object we had to type
cast the object to a string.
Line 2, get the destination as the selected item from the combo box.
Line 3, overwrites the value of kilometres by the value the distance text field.
Line 4, display using the label, Ensure that your output is the same as that of the
screen capture provided. The setText() method is found in any component
,basically it overwrites the value of the text of the component ,to the text
specified as a parameter.
Button [Delivery Cost] Question 1.2
private void btnDeliveryCostActionPerformed(java.awt.event.ActionEvent evt) {{
5. int position = (int) (lstKgs.getSelectedIndex());
6. double costTransport = 0;
7. switch (position)
8. {
9. case 0: costTransport = 0.6 * kilometres; break;
10. case 1: costTransport = 1.0 * kilometres; break;
Copyright 2015 X.S Maphumulo
33 | P a g e
Explanation
Line 5, The list class contains a method getSelectedIndex() which returns the
index of the selected item. According to the screen the selected item is 1 since in
programming we start counting from 0.
Line 6,instantiates the variable that will hold the transport cost
line 7 13, calculates the value of the transport cost .The selected index is used
to check for different cases .if the user selects the first category , position in line
5 will hold 0 then the transport cost will be calculated according to the case 0.
Line 14 17, checks whether chckSpeed is selected or not. If its selected R100
will be added to the transport cost.
Line 18, displays the transport cost to the text field.
If you take a close look in the parameter of the setText() method, you will see
that we didnt only display but we also formatted the value to 2 decimal places.
34 | P a g e
Explanation
I have commented the braces to not get you confused.
Line 2, checks whether the check box is selected, if yes then overwrites the value
of boxNumber to 4.
Line 6-12, the Boolean statement simply means IF chbSpeedPost (checkbox) is
not selected then do the following. So long as boxNumber is 4 the statement will
return a true then continue to acquire a random number until boxNumber is not
4, thats where the statement will return false then the compiler will stop
executing line 8.
Line 14,displays boxNumber to the text field
Explanation
Line 1, gets the bar code from the text field and store it to a variable sbarCode
Likely we are given the algorithm to follow when answering this question.
Read until you understand what is expected from you to write.
Line 2-3, creates two new variables and give them a value of zero.
Line 4, a for-loop stepping through each character of the bar code stored in
sbarCode.
Copyright 2015 X.S Maphumulo
35 | P a g e
Line 6, checks all numbers in the bar code that are in the logical even position.
Consider the following bar code
4373494603233
All the red numbers are in the logical even position while the blacks one are odd.
Line 8, we add all the numbers in logical even positions. Line 8 may also be
written as follows
sumEven += Integer.parseInt(sbarCode.substring(n, n + 1));
Line 10, all the numbers that are in logical odd positions are now added in line 12.
Line 14,According to the algorithm, before we get the total sum we must first
multiply the sum of odds by 3
Line 15, as per instruction of the algorithm, to get the check digit we must: 10
(sum modulus 10) which means we subtract the sum modulus 10 from 10.
Modulus means the remainder after division.
Line 16 23, verifies if the checkdigit is equivalent to the last digit of the bar code
,if that is true then the bar code is valid else its not valid.
1. {
2. String place = (String)(cmbCityName.getSelectedItem());
3. outputArea.setText(place+"\n");
4. Try
5. {
6. PrintWriter out = new PrintWriter(new FileWriter( "December2014"+place+".txt"));
7. for (int i = 0;i<arrDecDeliveries.length;i++)
8. {
9. if(arrDecDeliveries[i].indexOf(place) >=0)
10. {
11. outputArea.append(arrDecDeliveries[i]+"\n);
12. out.println(arrDecDeliveries[i]);
13. }
14. }
15. out.close();
16. }
17. catch (IOException e)
18. {
19.JOptionPane.showMessageDialog(null,"Error");
36 | P a g e
Explanation
Line 2-3, gets the place using the getSelectedItem() method of the
combo box then Line 3 we display the place. The escape character \n
is to prepare the next line for the next output.
Line 4 -16, the use of try catch statement is to avoid run-time errors as
we now dealing with external files. Line 6, we write to a file using the
PrintWriter class which takes the name of the file as a parameter.
Line 7, the one dimensional array arrDecDeliveries contains a date
and the name of the two cities.
Line 9, checks whether the place written exists, if it exists in the array
arrDecDeliveries the indexof() method will return a number greater
than 0.
Line 12 -15,writes the value of text to the file then close the file
If there is a problem with the external file the dialog message will be
displayed.
37 | P a g e
SECTION B
Composed of question 2!
Object Oriented Programming (OOP)
38 | P a g e
Introduction
Classes
Class is a template that contains similar objects. The object is referred to as the instance
of the class not the class itself. All along weve been using classes that are found inside
the library (JCL) to solve problems called predefined classes. In this section we will
develop and implement our own classes, user-defined classes.
Methods
In object oriented programming in order to use any member of a class we follow a
certain hierarchy.
For instance, lets consider a scenario where I want to format a decimal value to two
decimal places using DecimalFormat class.
Package/namespace:
import java.text.DecimalFormat;
39 | P a g e
Example:
We have an - Substring(int beginValue) which takes one parameter
We also have Substring(int begin ,int end) which takes two parameters
They both sit on the same class inside JCL. The signature is different because they
have different number of parameters. A signature may differ by a single letter.
This is called method overloading
Parameters are used to pass value from one class to another or one method to
another. The order of parameters must be the same in the method call and in the
method signature.
40 | P a g e
Constructor
A Constructor is a special method that assigns initial values to the
object(initializes the object)
There are two types of constructors
1. Default Constructor- this type contains no parameters and it may be
empty inside the body or may give initial values to the global members
of the class
2. Parameterized Constructor this type contains parameters and it
assigns members of the class to those parameters
Vehicle
Super Class
Sub-classes
Car
Truck
41 | P a g e
The unified Modelling Language (UML) provides a graphical tools that can be used
to describe a system
1. You are an IT educator to a school situated in Durban called Zwelibanzi. You were
asked to develop an e-Report for a subject that will be used by learners in a remote
location. Your software must allow a learner to choose the term and specify the subject
she/he wants to check results for.
Questions
1.1 Write a class called CReport and code it as follows
1.1.1 Declare the following data fields as private
sNameSurname name and surname (String)
sSubject - subject to view result for(String)
Copyright 2015 X.S Maphumulo
42 | P a g e
1.1.2 Write a default constructor and set to zero dPaper1 and dPaper2
1.1.3 Write a parameterized constructor to assign all data fields to their
Parameters. Each data field must have a parameter that is initialized to.
1.1.4 Write accessor methods for sNameSurname ,sSubject and sTerm.
1.1.5 Write a method called FinalMark() to calculate the final mark the method
must take the sum of the two marks(dPaper1 and dPaper2) then divided by
200. The method must return the rounded percentage of the two marks
1.1.6 Write a method Display() that will return a string as follows
If the returned percentage from FinalMark() is greater than zero but
less than 30 the method must return Fail
If the returned percentage from FinalMark() is greater than 30 but less
than 100 the method must return Pass
If the returned percentage from FinalMark() is greater than 80 but less
than 100 the method must return Pass with distinction
1.1.7 Write a method toString() that will return a concanated string .Copy and paste
the code below as it is.
return getTerm()+" "+getSubject()+" Report for "+ getNameSurname()+"\n"
+"The Final Mark is :"+ FinalMark()+"\n"+Display();
1.2
NB: there will be no code to copy and paste in the final exam
So its highly recommended that you understand this code
Go to form as show in the above screen capture, Under the button Report
[bntReport]
1.2.1 Write a code to get that data from all text fields and the combo box
1.2.2 Create an object of CReport and pass all the parameters
1.2.3 Output the method toString() in a dialog box
Solution
public class CReport {
//Question 1,1
//Question 1.1.1
private String sNameSurname;
private String sSubject;
private String sTerm;
Copyright 2015 X.S Maphumulo
43 | P a g e
{
this.sNameSurname=sNameSurname;
this.sSubject=sSubject;
this.sTerm =sTerm;
this.dPaper1=dPaper1;
this.dPaper2=dPaper2;
}
//Question 1.1.4
public String getNameSurname()
{
return sNameSurname;
}
public String getSubject()
{
return sSubject;
}
public String getTerm()
{
return sTerm;
}
//Question 1.1.5
public double FinalMark()
{
double dFinal = (dPaper1+dPaper2)*1.00/200;
double dFinalPerc = Math.round(dFinal *100);
return dFinalPerc;
}
//Question 1.1.6
public String Display()
Copyright 2015 X.S Maphumulo
44 | P a g e
{
String sDisplay = " ";
double dMark = FinalMark();
if(dMark>=0 && dMark <=30)
{
return sDisplay += "You Failed";
}
else if( dMark >=30 && dMark<=100)
{
return sDisplay += "You Passed";
}
else if(dMark>= 80 && dMark<=100)
{
return sDisplay +="Passed with a distinction";
}
else
{
return sDisplay +="Invalid Mark";
}
}
//Question 1.1.7
public String toString()
{
return getTerm()+" "+getSubject()+" Report for "+ getNameSurname()+"\n"
+"The Final Mark is :"+ FinalMark()+"\n"+Display();
}
}
//Question 1.2
Button- Reports [btnReports]
2. String sTerm = (String)cmbTerm.getSelectedItem();
3. String sNameSurname = txfNameandSurname.getText();
4. String sSubject = txfSubject.getText();
5. double dPaper1= Double.parseDouble(txfPaper1.getText());
6. double dPaper2= Double.parseDouble(txfPaper2.getText());
7. CReport report = new CReport(sNameSurname, sSubject, sTerm, dPaper1,
dPaper2);
8. JOptionPane.showMessageDialog(null,report.toString());
45 | P a g e
Explanation
Question 1.1.1
We declare the required data fields or members. Data fields must always be
declared as private unless stated otherwise. We ensure that we declare
them as high as we can so that they will be available to every scope hence
they are also termed global members of the classs
Question 1.1.2
It a good programming practice to always write a default constructor where
you give initial values to data members ,eventually they will be overwritten.
Question 1.1.3
Parameterized constructor (constructor with parameters) we created a
parameter for each data member and if you notice the names are exactly
the same. To not confuse the compiler since we have used the same names
we introduced the this-reference
The this-reference act as an arrow that tells the compiler that this member
of class is equivalent to this parameter
Public class Example {
private String sName;
public Example(String sName)
{
this.sName = sName;
}
If you find this confusing, you are allowed to not use the same
names for parameters and data members but also ensure the
order of parameters is the same.
Question 1.1.4
An accessor method is a method that returns a value. These methods will
help every time when we need the value of the returned variable.
46 | P a g e
Question 1.1.5
We instantiated a variable called dFinal, to calculate the weighted average
of the two papers.I multiplied by the factor 1.00 to change the expression
to a double type, from there I can now divide by 200.
Since we must return a percentage, I multiplied the value of dFinal by 100 ,
we now have the percentage .The Math.round() method is used to format
the percentage to 2 decimal places. We finally return dFinalperc with the
value of the formatted percentage.
Question 1.1.6
In an if-else statement each condition affects the value that will be
returned by the method, so in this question it wise to return a value of each
condition. We take the value returned in FinalMark() method by just calling
the method and assign it to a new local variable with the same data type,
double Mark. It was also possible to just use the method itself without
creating a new variable but for the readability sake lets stick on this
approach
Question 1.1.7
Master the principle of concatenation in java, you will never struggle to
write the body of the toString() method. Try to understand how I
concatenated each variable to another. The methods getTerm() ,
getSubject() and getNameSurname they just hold the value for
sTerm,sSubject and sNameSurname respectively.
Question 1.2 button Report
We get the term from the combo box using the method getSelectedItem()
that returns an object then we explicitly convert it to a string.
Gets the two papers
We instantiate the object of the CReport in order to connect with all the
members of the class.
CReport report = new CReport(parameters in their order)
We take all the variables instantiated in this form and pass them to the
CReport class.
We need to display the method toString() that holds a report which sits
inside the CReport class. JoptionPane as our dialog box then
report.toString() means in the CReport class take the toString() method .
47 | P a g e
SECTION C
Composed of question 3!
Problem Solving
48 | P a g e
Arrays A data structure that may contain variables of the same type.
Before you enter the exam room you should know to do the following:
Declare and Instantiate an array
Sort , Sum,average,median,highest,lowest and length
You should know how to remove Duplicates
Display a 2-dimensional array into a matrix
Copyright 2015 X.S Maphumulo
49 | P a g e
Defensive programming
Since we working with external files error handling is the crucial aspects
of this section
First technique is the try-catch statement
try
{
Body of the whole program
}
catch()
{
Display the message if there was an error
}
This statement is very useful when reading a textfile basically, it tells
the compiler to TRY and execute the source code then CATCH any runtime error that it may encounter.
If-else statement also plays a huge role in defensive programming and
validation
50 | P a g e
Move/Rename
if(file.exists()) {
file.renameTo(new File(NEW_FILENAME)); }
Before any operation you must first verify whether the file
exist else you will run into a run-time error
51 | P a g e
Text manipulation
Let consider a case where we want to manipulate data from a text file.The
data is delimited by a certain character. For instance, a whitespace or tab.
Example below shows how a text file is manipulated using the method split()
Example: You run a book store and you store all your books information in a
text file called Book.txt each line of data in the text file is structured as
follows
Code Book description Cost of the book
The screen print shows the first 4 lines of Book.txt
52 | P a g e
Output
Code
====
Book
e-Book
Book
Descripiton
=========
Java-with-xoh
Nighted
Perl
Cost
=====
R123.0
R200
R140
Explanation
Line 1,The bufferedReader class was instantiated to get the external file Book.txt
Line 2,sLine takes each line of the text file
Line 3, sLine is broken down into columns delimited (separated) by a tab.
then each column is temporarily saved to the new array sbook.
A tab was used as delimiter in this question however there are several delimiters.
The following ones are mostly used therefore you should know them
o \w - Matches any word character.
o \W - Matches any nonword character.
o \s - Matches any white-space character.
o \S - Matches anything but white-space characters.
Line 4 -6, The text file contains 3 columns: Code, Description and Cost
and they will be transferred to sbook[0],sbook[1] and sboo[2] accordingly.
sBook[0] = Code
sBook[1] = Descciption
Each column is saved in a new column
sBook[2] = Cost
Line 7-9, This display the heading : Code Description Cost
Line 8 , Underline the heading
Line 9 , append each column under it heading
53 | P a g e
54 | P a g e
55 | P a g e
56 | P a g e
57 | P a g e
Solution
The fragile and non-fragile item must be instantiated as global variables
18. }
19. txaOutput.setText("Loading progress display area: \n================\n\n");
20. txaOutput.append(String.format("%-20s%-25s%n", "Fragile items:",
fragileItems));
21. txaOutput.append(String.format("%-20s%-25s", "Non-fragile items:",
nonFragileItems));
Explanation
In line 1 , the variable that will hold the loading code was instantiated.
Line 2, we verify whether the radio button for fragile items was selected or not.
The method is isSelected() returns true or a false
Line 3, we secondly check if the length is less than 20 (for maximum fragile
items),if that is true then In Line 5 we overwrite the value of loadingCode
according to the instructions. F is for fragile items then the length will determine
how many asterisks
For instance if a user types F5 to the loading code text field
Copyright 2015 X.S Maphumulo
58 | P a g e
The output will 5 asterisks which implies that the following line of
States that the number after F is the length of the fragile items
And the asterisks will be displayed equally to the length
Line 6, if the length is less than 20 we will constantly concatenate an asterisk to
fragileItems ( global variable)
Line 8, we assume that if the radio button for fragile items is not selected, radio
button for non-selected item will be selected. Then we do the same process we
check if the loadingCode contains the length that is less than 30
The loadingCode is composed as follows
NFLength or NLength , length is a numerical value that will determined by the
number of asterisks that must be displayed
Line 14-15, once we get the loadingCode, we can then display it to the text area.
Line 15 , checks whether the loadingcode is null or it an empty string if it is we
then output an error message using a dialog
Line 19-21, the values of fragile items and non-fragile items is formatted then
displayed to the text area.
//Button [btnCheckload Check load status] Question 3.2
private void btnStatusActionPerformed(java.awt.event.ActionEvent evt) {
1. int numFragile = fragileItems.length
2. int numNonFragile = nonFragileItems.length();
3. double percFragile = (numFragile) / 20.0 * 100;
4. double percNonFragile = (numNonFragile) / 30.0 * 100;
5. txaOutput.setText(" Load status report:\n=====================\n");
txaOutput.append(String.format("%-15s%-25s%-15s%n", " Item type" "Number of items",
"Percentage loaded"));
6. txaOutput.append(String.format("%-15s%-25s%-13.2f%n", " Fragile", numFragile, percFragile));
7. txaOutput.append(String.format("%-15s%-25s%-13.2f%n", " Non-fragile",
numNonFragile, percNonFragile));
8. if (percFragile >= 50 && percNonFragile >= 50)
9. {
10. txaOutput.append("\n The delivery may progress.");
11. }
12. if (numFragile < 10 || numNonFragile < 15)
13. {
14. txaOutput.append("\n The delivery may not progress.");
15. if (numFragile < 10)
16. {
17. txaOutput.append("\n Number of fragile items still required : " + (10 - numFragile));
18. }
19. if (numNonFragile < 15)
20. {
21. txaOutput.append("\n Number of non-fragile items still required : " + (15 - numNonFragile));
Copyright 2015 X.S Maphumulo
59 | P a g e
22. }
23. }
24. }
Explanation
10
20
0.5
100 = 50%
From the equation above then we can conclude that the user who didnt get 50%
actual got less than 10. We verify if the user have less than 10 then inform the
user using the dialog box, the number that is required in order to have 50% then
continue with the delivery.
Line 18, the same thing in line 15-17 but in this case the maximum number for
non-fragile items is 30 then in order to get 50% the user must actually have 15
non-fragile items. We verify if the user have less than 15 then use a dialog to
inform the user the number of required non-fragile items in order to continue
with the delivery
10
30
0.5
100 = 50%
60 | P a g e
Explanation
Line 1-3 , overwrites the values of fragile and non-fragile items to an empty string
.Line 3 clear the text field
1. Consider the screen print below. Develop an algebraic calculator that will allow a
user to enter the values for a, b and c (quadratic) or m and c (linear) then use
those values to solve for x-intercept and y-intercept. Display both intercepts in
the dialog box.
Instruction
The user must select only one equation to solve
If selected both, display an error message.
Use a dialog to output the intercepts
2 4
2
61 | P a g e
62 | P a g e
63 | P a g e
64 | P a g e
65 | P a g e
66 | P a g e
67 | P a g e
68 | P a g e
69 | P a g e
70 | P a g e
71 | P a g e
72 | P a g e
73 | P a g e
74 | P a g e
75 | P a g e
76 | P a g e
77 | P a g e
78 | P a g e
79 | P a g e
80 | P a g e
81 | P a g e
82 | P a g e
83 | P a g e
84 | P a g e
85 | P a g e
86 | P a g e
87 | P a g e
88 | P a g e
89 | P a g e
90 | P a g e
91 | P a g e
92 | P a g e
93 | P a g e
94 | P a g e
95 | P a g e
96 | P a g e
97 | P a g e
98 | P a g e
99 | P a g e
100 | P a g e
101 | P a g e
102 | P a g e
103 | P a g e
104 | P a g e
105 | P a g e
106 | P a g e
107 | P a g e
108 | P a g e
109 | P a g e
110 | P a g e
111 | P a g e
112 | P a g e
113 | P a g e
114 | P a g e
115 | P a g e
116 | P a g e
117 | P a g e
118 | P a g e
119 | P a g e
120 | P a g e
121 | P a g e
122 | P a g e
123 | P a g e
124 | P a g e
125 | P a g e
126 | P a g e
127 | P a g e
128 | P a g e
129 | P a g e
130 | P a g e
131 | P a g e
132 | P a g e
133 | P a g e
134 | P a g e
135 | P a g e
136 | P a g e
137 | P a g e
138 | P a g e
139 | P a g e
140 | P a g e
141 | P a g e
142 | P a g e
143 | P a g e
144 | P a g e
145 | P a g e
146 | P a g e
147 | P a g e
148 | P a g e
149 | P a g e
150 | P a g e
151 | P a g e
152 | P a g e
153 | P a g e
154 | P a g e
155 | P a g e
156 | P a g e
157 | P a g e
158 | P a g e
159 | P a g e
160 | P a g e
161 | P a g e
162 | P a g e
163 | P a g e
164 | P a g e
165 | P a g e
166 | P a g e
167 | P a g e
168 | P a g e
169 | P a g e
170 | P a g e
171 | P a g e
172 | P a g e
173 | P a g e
174 | P a g e
175 | P a g e
176 | P a g e
177 | P a g e
178 | P a g e
179 | P a g e
180 | P a g e
181 | P a g e
182 | P a g e
183 | P a g e
184 | P a g e
185 | P a g e
186 | P a g e
187 | P a g e
188 | P a g e
189 | P a g e
190 | P a g e
191 | P a g e
192 | P a g e
193 | P a g e
194 | P a g e
195 | P a g e
196 | P a g e
197 | P a g e
198 | P a g e
199 | P a g e
200 | P a g e
201 | P a g e
202 | P a g e
203 | P a g e
204 | P a g e
205 | P a g e
206 | P a g e
207 | P a g e
208 | P a g e
209 | P a g e
210 | P a g e
211 | P a g e
212 | P a g e
213 | P a g e
214 | P a g e
215 | P a g e
216 | P a g e
217 | P a g e
218 | P a g e
219 | P a g e
220 | P a g e
221 | P a g e
222 | P a g e
223 | P a g e
224 | P a g e
225 | P a g e
226 | P a g e
227 | P a g e
228 | P a g e
229 | P a g e
230 | P a g e
231 | P a g e
232 | P a g e
233 | P a g e
234 | P a g e
235 | P a g e
236 | P a g e
237 | P a g e
4. Using the above screen capture. Develop an application with which you and your
friend can exchange secret messages .The button Encode and save must encode
the content of the text area by changing it to a reversed form, the content of the
text area then save it to a text file. The button read and decode must first decode
the content from the reversed state to the original state (readable) then display it
to the text area.
Example:
5. Using Exercise 3 above, Develop the same application but this time use classes
and methods to add functionalities.
Write a class called CMessage with the following methods
A mutator method Save () that will encode the content and save it.
A mutator method Read () that will read and display the content.
It a problem solving so there are no restrictions you can use methods with
parameters and other strategies so long as the two mentioned methods are
found inside the class.
NOTE: You must connect the class with the graphical user interface.
238 | P a g e
Solution to Exercise 1
private void btnSolutionActionPerformed(java.awt.event.ActionEvent evt) {
1. double m = Double.parseDouble(txfLinearM.getText());
2. double c = Double.parseDouble(txfLinearC.getText());
3. double xLinear = (-1*c*1.00)*m;
4. double yLinear = c;
5. double a= Double.parseDouble(txfQuadraticA.getText());
6. double b= Double.parseDouble(txfQudraticB.getText());
7. double C= Double.parseDouble(txfQuadraticC.getText());
8. double xQuad1 = ((-1*b ) + Math.sqrt(Math.pow(b,b) - (4*a*C)))/2.0*a;
9. double xQuad2 = ((-1*b ) - Math.sqrt(Math.pow(b,b) - (4*a*C)))/2.0*a;
10. double yQuad = C;
11. String sLinear = "The solution for Linear equation :\n x="+xLinear +" and y="+ yLinear ;
12. String sQuadratic = " The solution for the quadratic equation :\n"
13. +"x=" + xQuad1 +" or x ="+xQuad2 +", y="+yQuad;
14. if(radbtnLinear.isSelected() && radbtnQuadratic.isSelected())
15. {
16. JOptionPane.showMessageDialog(null,"Select only one equation");
17. }
18. else
19. {
20. if(radbtnLinear.isSelected())
21. {
22. JOptionPane.showMessageDialog(null,sLinear);
23. }
24. else if( radbtnQuadratic.isSelected())
25. {
26. JOptionPane.showMessageDialog(null,sQuadratic);
27. }
28. else
29. {
30. JOptionPane.showMessageDialog(null,"Please select at least one radio button");
31. }
32. }
Solutions for exercise 2, 3 and 4 will be posted on the ftp server or you can email me will
239 | P a g e
240 | P a g e
241 | P a g e
242 | P a g e
243 | P a g e
244 | P a g e
245 | P a g e
246 | P a g e
247 | P a g e
248 | P a g e
249 | P a g e
250 | P a g e
251 | P a g e
252 | P a g e
253 | P a g e
254 | P a g e
255 | P a g e
256 | P a g e
257 | P a g e
258 | P a g e
259 | P a g e
260 | P a g e
261 | P a g e
262 | P a g e
263 | P a g e
264 | P a g e
265 | P a g e
266 | P a g e
267 | P a g e
268 | P a g e
269 | P a g e
270 | P a g e
271 | P a g e
272 | P a g e
273 | P a g e
274 | P a g e
275 | P a g e
276 | P a g e
277 | P a g e
278 | P a g e
279 | P a g e
280 | P a g e
281 | P a g e
282 | P a g e
283 | P a g e
284 | P a g e
285 | P a g e
286 | P a g e
287 | P a g e
288 | P a g e
289 | P a g e
290 | P a g e
291 | P a g e
292 | P a g e
293 | P a g e
294 | P a g e
295 | P a g e
296 | P a g e
297 | P a g e
298 | P a g e
299 | P a g e
300 | P a g e
301 | P a g e
302 | P a g e
303 | P a g e
304 | P a g e
305 | P a g e
306 | P a g e
307 | P a g e
308 | P a g e
309 | P a g e
310 | P a g e
311 | P a g e
312 | P a g e
313 | P a g e
314 | P a g e
315 | P a g e
316 | P a g e
317 | P a g e
318 | P a g e
319 | P a g e
320 | P a g e
321 | P a g e
322 | P a g e
323 | P a g e
324 | P a g e
325 | P a g e
326 | P a g e
327 | P a g e
328 | P a g e
329 | P a g e
330 | P a g e
331 | P a g e
332 | P a g e
333 | P a g e
334 | P a g e
335 | P a g e
336 | P a g e
337 | P a g e
338 | P a g e
339 | P a g e
340 | P a g e
341 | P a g e
342 | P a g e
343 | P a g e
344 | P a g e
345 | P a g e
346 | P a g e
347 | P a g e
348 | P a g e
349 | P a g e
350 | P a g e
351 | P a g e
352 | P a g e
353 | P a g e
354 | P a g e
355 | P a g e
356 | P a g e
357 | P a g e
Prefix
Description
Example
Txf /txt
lbl
btn
radbtn
cmb
frm
timer
Text field
label
button
Radio button
Combobox
form
tmr
txfName
lblDisplay
btnReport
radbtnLinear
cmbGender
frmHome
tmrCount()
Variables
Variables of the primitive type are prefixed as follows
float - f
int , int32 - i
double - d
boolean - is/her
char - c
String s
358 | P a g e
Loops counters and variables for capacity are not necessarily prefixed. It is convention
use i, j, k (for loop counters) and n or m for observations or array lengths.
Arrays
Arrays are prefixed with arr for instance arrNames means an array of names. The
programmer may write the full word without the prefix arr since arrays are collections.
Classes
In this guide I used a convention called Pascal case where a class is prefixed with the
capital letter C.
Description of the escape sequence
Escape Sequence
\b
\t
\n
\f
\r
\
\
\\
Description
backspace
Tab
Next line
Form feed
Carriage return
Double quotation mark
Single quotation mark
backslash
Access to methods
Access modifier
public
private
Protected
Description
Any class can use this method
Use by the class only protected data
Method(member) accessible in a class ,
other class in the same package and
subclasses outside the package
359 | P a g e
Bibliography
Approach