Java With Xoh for Exams
-
Upload
xolani-maphumulo -
Category
Documents
-
view
49 -
download
1
description
Transcript of Java With Xoh for Exams
1 | P a g e
Copyright © 2015 X.S. Maphumulo
Publishers and Copyright laws
No part of this publication may be reproduced, stored in a retrieval
system, or transmitted, in any form, or by any means, electronic,
mechanical, photocopying, recording, or otherwise, without the prior
consent of the publisher.
For modifications contact the author
Email: [email protected] or [email protected]
Contact number: 0612375781
2 | P a g e
Copyright © 2015 X.S. Maphumulo
The Author
Xolani Samkelo Maphumulo, author of this hands-on java guide, is a
first year student in Computer Science at the University of the Free State. He lives
in Durban and he has been a java basic coder for 3 years in Zwelibanzi High school
situated in Durban. He is an excellent junior coder in both languages C# and java
and He feels so incline to share his knowledge with matriculates of 2015 for the
upcoming final exams.
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.
Who is this guide for, what does it cover and
what you need in order to use it
This guide is designed specifically for current matriculates as a tool to get them on
the road for the upcoming final examination in Information Technology Paper 1.I
do not teach you the syntax of the java language but I teach how to program, so
follow as I do the previous past papers using different approaches. The guide also
consists of complex exercises that will prepare you for the exam and the solutions
are provided at the end of the book. Netbeans 7.3.1 is used to compile all the
solutions included but other versions will also support the source code of each
question. Variable’s names and controls such as buttons are changed according to
a naming convention specified in APPENDIX A.
3 | P a g e
Copyright © 2015 X.S. Maphumulo
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
Section C Problem solving
Arrays in 1 dimensional and 2D
Reading ,Writing and Manipulation of Text Files
String manipulation
Dynamic instantiation of objects
Solutions
Appendix A – Naming conventions, data types, Access modifiers and escape
characters
4 | P a g e
Copyright © 2015 X.S. Maphumulo
SECTION A
Composed of question 1!
General programming skills
To use string classes in complex problems
To use math classes and format your output
To apply programming techniques such as loops
And defensive programming.
5 | P a g e
Copyright © 2015 X.S. Maphumulo
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 Summary of strings methods
The prefixed data type indicate indicates the return value
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
“Whether you want to uncover the secrets of the
universe, or you want to pursue a career in the 21st
century, Basic computer programming is an
essential skill to learn”
~ Stephen Hawking
6 | P a g e
Copyright © 2015 X.S. Maphumulo
String classes and methods
char charAt (int index): It returns the character at the specified index. Specified
index value should be between 0 to length () -1 both inclusive.
boolean equals(Object obj): Compares the string with the specified string and
returns true if both matches else false.
boolean equalsIgnoreCase(String string): It works same as equals method but it
doesn’t consider the case while comparing strings. It does a case insensitive
comparison.
int compareTo(String string): This method compares the two strings based on the
Unicode value of each character in the strings.
int compareToIgnoreCase(String string): Same as CompareTo method however it
ignores the case during comparison.
boolean startsWith(String prefix, int offset): It checks whether the substring
(starting from the specified offset index) is having the specified prefix or not.
int lastindexOf(String str): Returns the index of last occurrence of string str.
String substring(int beginIndex): It returns the substring of the string. The substring
starts with the character at the specified index.
String substring(int beginIndex, int endIndex): Returns the substring. The substring
starts with character at beginIndex and ends with the character at endIndex.
String replace(char oldChar, char newChar): It returns the new updated string after
changing all the occurrences of oldChar with the newChar.
boolean contains(CharSequence s): It checks whether the string contains the
specified sequence of char values. If yes then it returns true else false.
int length(): It returns the length of a String
String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()
7 | P a g e
Copyright © 2015 X.S. Maphumulo
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 int numb= Math.abs(-5);
//=5
exp(a) Gives ea Double ex = Math.exp(1); // =2.71
max(x,y) Largest of arguments x and y
Int max =Math.max(3,4); //=4
min(x,y) Smallest of arguments ,x and y
Int min =Math.min(3,4); //=3
pow(a,b) Gives ab double pwr=Math.pow(2,5); //=32
round(x) Nearest integer to x double n=Math.round(13.6); //=14
sqrt(x) Square root of x double sqrt =Math.sqrt(25); //=5
Reference
1) Marietjie Havenga & Christina Moraal,
(2007),Creative programming in java part 2 ,BitaByte
PTY (ltd)
8 | P a g e
Copyright © 2015 X.S. Maphumulo
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
}
A Boolean condition is any statement that only returns true or
false. For instance, marks>=50 the result will be true only if the
marks is greater or equivalent to 50, else false .An if- statement
may contain a compound boolean condition :
if ((marks>=50 && marks <60 )||(marks==60))
The switch statement
Switch statement fulfils the same role as an if- statement and
everything that can be done with a switch can also be done with an
if-statement, but not the other way around. The structure of a
switch is shown in example 3.
9 | P a g e
Copyright © 2015 X.S. Maphumulo
The conditional operator (also known as the ternary operator)
The conditional operator has the following structure:
(Test expression)? (Results if true): (Results if false)
Consider the following example:
String sResult = (marks>=50)? “Pass”: “Fail”;
As always, the right-hand side of an assignment must be evaluated
first
The conditional expression is evaluated first and if it is true, the
value “Pass” is assigned to sReport else the value “Fail” is assigned to
sReport.
According to the specified naming convention in Appendix A, each
variable is prefixed with the first letter of it type e.g. sReport is a
string type
Table below shows Logic operators for Boolean conditions
Operator Description
== Equal to
!= Not equal to
>= Greater than or equal to
<= Smaller than or equal to
&& AND
|| OR
^ XOR
! NOT
10 | P a g e
Copyright © 2015 X.S. Maphumulo
I will not do all the previous papers , apart that from
being impossible ,this guide doesn’t focus on the quantity
of information but it focuses on the quality by giving you
best strategies to program and to find the fast and
effective algorithms of any java problem you will
encounter in the future.
LetStart(“With Xolani”);
if(result.LeftBehind()==true)
{
string promise = “ I will pick you up “;
this.GoTogetherAgain(I.promise);
}
11 | P a g e
Copyright © 2015 X.S. Maphumulo
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
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
Surname Initial (age)
Gender
University
12 | P a g e
Copyright©2015 X.S. Maphumulo
Example: Nicklaus Jobs, who was born in 1995 and studies at the University of the Free State.
Solution
It’s 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
Copyright©2015 X.S. Maphumulo
//button – [User profile ]
private void btnUserProfileActionPerformed(java.awt.event.ActionEvent evt)
{
1. sName = txfName.getText();
2. sSurname = txfSurname.getText();
3. sDate = txfDateofBirth.getText();
4. String sGender = (String)cmbGender.getSelectedItem();
5. cInitial = sName.charAt(0);
6. String date = sDate.substring(6);
7. int Age =2015- Integer.parseInt(date);
8. String sNameTag = " ";
9. String university= " ";
10. if(Age>=18 && Age<=21)
11. {
12. if(radbtnUKZN.isSelected() && radbtnUFS.isSelected())
13. {
14. JOptionPane.showMessageDialog(null," Please select only 1 university");
15. }
16. else
17. {
18. if( radbtnUKZN.isSelected() )
19. {
20. university = "University of Kwa-Zulu Natal";
21. }
22. else if( radbtnUFS.isSelected() )
23. {
24. university= "University of the Free state";
25. }
26. else
27. {
28. JOptionPane.showMessageDialog(null," Select at least one university");
29. }
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. }
14 | P a g e
Copyright©2015 X.S. Maphumulo
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
Copyright©2015 X.S. Maphumulo
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.
//button – [New user]
private void btnNewUserActionPerformed(java.awt.event.ActionEvent evt) {
1. txfSurname.setText("");
2. txfName.setText("");
3. txfDateofBirth.setText("");
4. txtAreaOutput.setText("");
5. JOptionPane.showMessageDialog(null," You may input all your details");
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
Copyright©2015 X.S. Maphumulo
//button – [Generate code]
private void btnGeneratePinActionPerformed(java.awt.event.ActionEvent evt) {
1. char sLast = sSurname.charAt(sSurname.length()-1);
2. int number =(int)Math.random()*10;
3. String sPin = cInitial + String.valueOf(number) + sLast;
4. txtAreaOutput.append(sPin.toUpperCase());
Explanation
Line 1, We are required to take the last character of the surname to formulate
the code
Let’s visits arrays. Since arrays are zero-based (starts from zero) then every set
of length N the last term will be N-1.
X O L A N I
0 1 2 3 4 5
We could see that the actual length of the word”xolani” 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
17 | P a g e
Copyright©2015 X.S. Maphumulo
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
18 | P a g e
Copyright©2015 X.S. Maphumulo
followed by a dot the intelliSpaense will give you options and since they are self-
explanatory, 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
Copyright©2015 X.S. Maphumulo
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
user’s details below the two amounts.
Your report must be as follows:
Use the following formulas to calculate for investments amount
1) A = P (1+i x n) – Simple interest
2) A = P (1+I )2 - Compound interest
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
Copyright©2015 X.S. Maphumulo
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
Copyright©2015 X.S. Maphumulo
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
Copyright©2015 X.S. Maphumulo
26. switch( month)
{
case 1: sMonth += "January";break;
case 2: sMonth += "February";break;
case 3: sMonth += "March";break;
case 4: sMonth += "April";break;
case 5: sMonth += "May";break;
case 6: sMonth += "June";break;
case 7: sMonth += "July";break;
case 8: sMonth += "August";break;
case 9: sMonth += "September";break;
case 10: sMonth += "October";break;
case 11: sMonth += "November";break;
default:sMonth += "December ";break;
27. }
28. sDateOfBirth = day + " "+ sMonth+ " "+ year;
29. }
30. double dAmountInSimple= Math.round( dAmountInvest*( 1+ dPercentage*iYears ) );
31. double dAmountCompound = dAmountInvest * Math.pow(1 + dPercentage, iYears);
32. double dAmountCompoundInvest = Math.round(dAmountCompound);
33. String sOutput= " ";
34. sOutput += "Simple Interest : "+dAmountInSimple+ "\n Compound Interest :
"+dAmountCompoundInvest+"\n";
35. sOutput += "Date of birth : "+sDateOfBirth+ " \nClient : "+ sSurname+ " "+cInitial + " \n";
36. sOutput+= "Gender : "+sGender;
37. JOptionPane.showMessageDialog(null,sOutput.toUpperCase());
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
Copyright©2015 X.S. Maphumulo
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.
24 | P a g e
Copyright©2015 X.S. Maphumulo
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
Copyright © 2015 X.S Maphumulo
//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.
32 | P a g e
Copyright © 2015 X.S Maphumulo
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.
//button – [Delivery] Question 1.1
private void btnDeliveryActionPerformed(java.awt.event.ActionEvent evt) {
1. String departure = (String) (cmbDepart.getSelectedItem());
2. String destination = (String) (cmbDestination.getSelectedItem());
3. kilometres = Integer.parseInt(txfDistance.getText());
4. lblDelivery.setText(departure + " to " + destination + " : " + kilometres + "km");
}
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;
33 | P a g e
Copyright © 2015 X.S Maphumulo
11. case 2: costTransport = 1.25 * kilometres; break; 12. case 3: costTransport = 1.65 * kilometres; break; 13. } 14. if (chbSpeedPost.isSelected()) 15. { 16. costTransport += 100; 17. } 18. txfCost.setText(String.format("R%2.2f",costTransport));
}
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 didn’t only display but we also formatted the value to 2 decimal places.
Button – [Delivery box Number] Question 1.3
private void btnBoxNumberActionPerformed(java.awt.event.ActionEvent evt) {
1. int boxNumber = 0;
2. if (chbSpeedPost.isSelected())
3. {
4. boxNumber = 4;
5. }
6. else
7. { //opening the else statement
8. do
9. {
10. boxNumber = (int) (Math.random() * 5) + 1;
11. } //closing do-while
12. while (boxNumber == 4);
13. } //closing the else statement
14. txfBoxNumber.setText("" + boxNumber);
}
34 | P a g e
Copyright © 2015 X.S Maphumulo
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, that’s where the statement will return false then the compiler will stop executing line 8.
Line 14,displays boxNumber to the text field
Button - [Validate bar code] Question 1.4 private void btnBarCodeActionPerformed(java.awt.event.ActionEvent evt) {
1. String sbarCode = txfBarCode.getText(); 2. int sumOdd = 0; 3. int sumEven = 0; 4. for (int n = 0; n < sbarCode.length()-1; n ++) 5. { 6. if ((n+1) % 2 ==0) 7. { 8. sumEven = sumEven + Integer.parseInt(sbarCode.substring(n, n + 1)); 9. } 10. else 11. { 12. sumOdd = sumOdd + Integer.parseInt(sbarCode.substring(n, n + 1)); 13. } 14. int sum = sumOdd * 3 + sumEven; 15. int checkDigit = 10 - (sum % 10); 16. if(checkDigit == Integer.parseInt(sbarCode.substring(sbarCode.length()-1))) 17. { 18. txfDisplayBarCode.setText("The bar code is valid. Check digit: " + checkDigit); 19. } 20. else 21. { 22. txfDisplayBarCode.setText("NOT valid. Correct check digit: " + checkDigit); 23. }
}
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.
35 | P a g e
Copyright © 2015 X.S Maphumulo
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 it’s not valid.
Button - [view and save deliveries] Question 1.5
I gave the background information about text files on section C so bear with me and browse section C before you try to answer this question. private void btnViewDeliveriesActionPerformed(java.awt.event.ActionEvent evt)
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
Copyright © 2015 X.S Maphumulo
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
Copyright © 2015 X.S Maphumulo
SECTION B
Composed of question 2!
Object Oriented Programming (OOP)
Develop a class, including data fields and methods
Write parameterized methods that return a value
Develop different constructors
To apply programming techniques such as loops
Defensive programming.
38 | P a g e
Copyright © 2015 X.S Maphumulo
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 we’ve 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, let’s consider a scenario where I want to format a decimal value to two
decimal places using DecimalFormat class.
Package/namespace: import java.text.DecimalFormat;
Object instantiation: DecimalFormat f = new DecimalFormat("0.00");
method : System.out.println(f.format(16.5666));
In order to access the method format we must have a package then a class and method.
Method signature- is composed of the access modifier, return type, method name and
parameters
public int getSum(int iNum1,int iNum2)
The above method shows a method signature
Access modifier – is public which means you can access the method from other
classes .If the method is private it’s not accessible to external classes. We declare
data fields and methods as private if we want to enforce business rules or
validation.
The return type- the above method returns an integer and to indicate which type
is returned by the method ,you must include that type in the signature.Methods
that returns a value are called accessor methods
and methods that does not return a value are called mutator methods.Mutator
methods are mostly used for displaying and to pass parameters.
The method name, is the most significant part of the method signature. A class
may have more than one method with the same name as long as the signature is
different.
39 | P a g e
Copyright © 2015 X.S Maphumulo
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.
The static and non-static keywords
The keyword static plays a huge role to a programmer
Once the method is declared with a keyword static, a programmer does not have to
instantiate the object of a class in order to use that method.
Non-static methods
Non static methods are called instances. A programmer must instantiate the object in
order to use the method.
Main Method
This is the most crucial method in any programming language. Everything that is written
to any class must be called inside the main method in order for it to be executed. The
following code shows the main method signature
public static void main(String[]args)
Access modifier – public so that everyone may access it.
Static – It’s a static method, hence you don’t have to instantiate any object before
you call the main method
void – The return type indicate it doesn’t return a value but output everything
inside it
main- it just a name for the method
String[]args - it passes a string array as an argument or parameter
40 | P a g e
Copyright © 2015 X.S Maphumulo
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
Advanced Object Oriented programming
Inheritance
Inheritance – A technique used to form new classes, using existing classes as super or
base class of the new formed classes. The new classes are now called subclasses and
they inherits all the members of the super or base class, such as object, methods, data
fields and properties.
Advantages
Makes implementing new classes quick
Fewer errors
Programming becomes easier and understandable
A Flow chart showing the principle of inheritance
Super Class
Sub-classes
Vehicle
Car Truck
41 | P a g e
Copyright © 2015 X.S Maphumulo
The unified Modelling Language (UML) provides a graphical tools that can be used
to describe a system
Encapsulation – refers to the packaging of data fields and behaviors into a
single unit (class) so that implementation details are hidden and access is
restricted.
Polymorphism – refers to the ability of the objects belonging to different classes
respond to a method, field, or property calls of the same time.
Abstraction – refers to the mechanism through which details can be reduced and
factored out so that one can focus on a few concepts at a time. 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)
42 | P a g e
Copyright © 2015 X.S Maphumulo
sTerm – the term ( String)
dPaper1- the marks for paper 1 (double)
dPaper2-marks for paper 2 (double)
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();
NB: there will be no code to copy and paste in the final exam
So it’s highly recommended that you understand this code
1.2 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;
43 | P a g e
Copyright © 2015 X.S Maphumulo
private double dPaper1;
private double dPaper2;
//Question 1.1.2
public CReport()
{
dPaper1= 0;
dPaper2=0;
}
//Question 1.1.3 public CReport(String sNameSurname,String sSubject,String sTerm,double dPaper1,double dPaper2)
{
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()
44 | P a g e
Copyright © 2015 X.S Maphumulo
{
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
Copyright © 2015 X.S Maphumulo
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
Copyright © 2015 X.S Maphumulo
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 let’s 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
Copyright © 2015 X.S Maphumulo
SECTION C
Composed of question 3!
Problem Solving
To Read , Write and Manipulate an external text file
To apply advanced string manipulation
Use complex operations to arrays
48 | P a g e
Copyright © 2015 X.S Maphumulo
External text files
Until now all the programs we wrote, data is saved in the random static
memory hence we always have to enter it from scratch each and every time
when we run the program. JCL provides classes that can be used to
permanently store data that we execute on our programs, then later we just
read the stored data. The class PrintWriter and BufferedReader can be used
to store data in a text file and also read the data later.
The basic code to write to a text file
PrintWriter writer = new PrintWriter(new FileWriter(“filename.txt”);
writer.println(“Type what you want to save to a text file”);
writer.close()
The basic code to read from a text file
BufferedReader br = new BufferedReader(new FileReader(“filename.txt”);
String sLine = br.readLine();
System.out.println(sLine+ “\n”);
Br.close();
Using a Scanner class to read from a text file
File text = new File(“filename.txt”);
Scanner scnr = new Scanner(“filename.txt”);
while(scnr.hasNextLine()){
String line = scnr.nextLine();
System.out.println(line +”\n”);
}
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
49 | P a g e
Copyright © 2015 X.S Maphumulo
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 run-
time error that it may encounter.
If-else statement also plays a huge role in defensive programming and
validation
50 | P a g e
Copyright © 2015 X.S Maphumulo
The File Class
The file class provides us with the static methods for the creation, deletion,
moving and opening files.
File file = new File(filename);
To check if a file exist
If(file.exists())
{
Code if the file exists
}
else
{
File does not exist
}
Deleting a files
If(file.exists())
{
f.delete();
}
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
Copyright © 2015 X.S Maphumulo
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 book’s 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
Code that reads a Book.txt object
1. BufferedReader in = new BufferedReader( new FileReader("Books.txt")); 2. String line = in.readLine(); 3. String[] sbook = line.split("\t"); 4. String code = sbook[0]; 5. String description = sbook[1]; 6. String price = sbook[2]; 7. System.out.printf("%-12d%-12d%07d\n","Code","description","price"); 8. System.out.printf("%-12d%-12d%07d","======","========","========""); 9. System.out.printf("%-12d%-12d%07d\n",code,description,price); 10. in.close();
52 | P a g e
Copyright © 2015 X.S Maphumulo
Output
Code Descripiton Cost
==== ========= =====
Book Java-with-xoh R123.0
e-Book Nighted R200
Book Perl 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.
o \d - Matches any digit.
o \D - Matches anything except digits.
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
57 | P a g e
Copyright © 2015 X.S Maphumulo
Solution
The fragile and non-fragile item must be instantiated as global variables
// Button – [btnLoad Load item] 3.1
private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {
1. String loadingCode = "";
2. if (rbtFragile.isSelected())
3. { if (fragileItems.length() < 20)
4. {
5. loadingCode = "F" + (fragileItems.length() + 1);
6. fragileItems += "*";
7. }
8. } else
9. {
10. if (nonFragileItems.length() < 30)
11. {
12. loadingCode = "NF" + (nonFragileItems.length() + 1);
13. nonFragileItems += "*"; }
14. } txfLoadingCode.setText(loadingCode);
15. if (loadingCode.equals(""))
16. {
17. JOptionPane.showMessageDialog(null, "Loading of item cannot be processed - No loading
space\n", "Information", WIDTH);
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
58 | P a g e
Copyright © 2015 X.S Maphumulo
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));
59 | P a g e
Copyright © 2015 X.S Maphumulo
22. }
23. }
24. }
Explanation
Line 1-2,gets the length of the of fragile and non-fragile items
Line 3-4, The maximum number of fragile items must be 20
then we calculate the percentage of the fragile items.
The non-fragile have a maximum of 30 so compute the quotient then get the
percentage.
Line 5-7, For readability the heading is underlined then in Line 6-7 we display the
percentages of the fragile and non-fragile items
Line 8,We use a compound if-else statement to check if both of the computed
percentages are greater than 50 .The dialog message only indicates that they are
greater than 50 . Do not confuse the following two:
&& - logic AND used when both condition must be true.
|| - logic OR used when one of the two conditions must be true.
Line 14, if both of the percentages are not greater or equivalent to 50 then we
output a dialog message, informing the user that he/she may not continue with
the delivery
Line 15-17 , Remember the maximum number for fragile items is 20 then in order
to have 50% of fragile items so that a user may continue with the delivery, he/she
must actually have a length of 10 fragile items:
10 20 0.5 100 = 50% From the equation above then we can conclude that the user who didn’t 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
Copyright © 2015 X.S Maphumulo
//Button – [btnClear Clear load] Question 3.3
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
1. fragileItems="";
2. nonFragileItems="";
3. txaOutput.setText("");
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𝑎 Use it to solve for the x-intercept
61 | P a g e
Copyright © 2015 X.S Maphumulo
2. As a challenge re do exercise 1 but now allow the user to select both
radio buttons and output both solution in Dialog, The solution must not
be a number only but it must show steps, show factors before you
arrive at the final answer.
3. Write a concise description in two text files, the descriptions are about
programming (“programming.txt”) and artificial intelligence
(intelligence.txt) .Allow a user to select from the combo box which
description to read and then also write a code to read that specified
text file in the Button Display Description.
Example: If a user select Programming
“You might not think that that programmers are artists,
but programming is an extremely creative profession .It’s
Logic-based creativity”
~John Romero
237 | P a g e
Copyright © 2015 X.S Maphumulo
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: if a user types “Xolani” then it must saved as “inaloX” to a text file.
To read it must be changed from “inalox” to “Xolani”.
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
Copyright © 2015 X.S Maphumulo
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
forward them to your email account.
356 | P a g e
Copyright © 2015 X.S Maphumulo
This appendix specifies the following
Explains the naming conventions and how to give names to Variables, classes and controls.
It summarizes methods and classes that found in the JCL (library)
Contains links for useful resources and sites
Provides the history of java and Why the author chose java
357 | P a g e
Copyright © 2015 X.S Maphumulo
The purpose of naming conventions is to facilitate easier maintenance of code. This is
accomplished by naming all entities in a java program such that
It can be distinguished from other entities
Its function is evident
Its class type can be identified
If we stick to jTextbox1, jTextbox2, jButton1 etc. as controls were named by Netbeans,
we will soon run into trouble to comprehend the purpose of controls or variables, to
follow the logic of a piece of code and to maintain the code.
The following table shows how controls are named however some of the controls are
not mentioned here.
Prefix Description Example
Txf /txt Text field txfName
lbl label lblDisplay
btn button btnReport
radbtn Radio button radbtnLinear
cmb Combobox cmbGender
frm form frmHome
timer tmr 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
Copyright © 2015 X.S Maphumulo
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 Description
\b backspace
\t Tab
\n Next line
\f Form feed
\r Carriage return
\” “ Double quotation mark
\’ Single quotation mark
\\ backslash
Access to methods
Access modifier Description
public Any class can use this method
private Use by the class only –protected data
Protected Method(member) accessible in a class ,
other class in the same package and
subclasses outside the package