Programming Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 416

CPR3013 Week 04

A Couple of Classes
Topics
• This week we will look at two predefined
Java classes
– String
• because strings are useful and we need them in
our example programs
– Scanner
• because we need a way of obtaining keyboard
input for our programs
Objects and Primitive Data
• There are two divisions of data in Java
Objects
• An object consists of both data and
methods.
• A class is the data type of an object.
– A class describes what an object of a
particular type is made of, its data and its
methods.
– A class is merely a description
methods
(little programs)
to process data
String class
• String objects
– contain a sequence of characters,
– and various methods that can do things
with those characters
There are several
dozen methods in
a String object
Question
• What do you suppose that the length()
method of the String object does?

It computes the length of a String


Creating a String Object
class StringDemo1
{
public static void main ( String[] args )
{
String str ;
str = new String( “A CG047 String!" );
}
}
Question
• How can we change the program so that
it creates a String object with the value
“How exciting”

str = new String( “How exciting” );


Using a Method
class StringDemo2
{
public static void main ( String[] args )
{
String str;
int len;
str = new String( "Elementary, my dear Watson!" );
len = str.length();
System.out.println("The length is: " + len );
}
}
Dot Notation
• If you want to run a method of the
object, use the method name.
• If it needs parameters (values supplied
to the method), they go inside ( ) like
this:
objectReference.methodName( parameter )

• Always use ( ) with a method name, even


if it needs no parameters.
Exercise to do outside class!
• Compile and run the program StringDemo2
• Change the String in various ways and
observe the effect on the computed string
length.
– Add extra spaces on either side and in the
middle of the string;
– add more punctuation;
– insert a tab character (a real tab character,
not just spaces).
• Note that the length of the string
"MMMMMM" is the same as "iiiiii".
A Method that Creates a String
class StringDemo3
{
public static void main ( String[] args )
{
// create the original object
String = new String( "Elementary, my dear Watson!" );
//create a new object from the original
String sub = str.substring(8);
System.out.println( sub );
}
}
explanation
• The clause
str.substring(8)
creates a new String object,
– that contains its own data,
– which are characters copied from the original
string.
– The copy starts with the 8th character of the
original string and continues to the end.
• Character numbering starts at zero, so the
8th character in the original string is the
first ‘r’
Question
• What characters are contained in the
new object?

ry, my dear Watson!


Other Methods of String
• public char charAt( int index )
• public String concat( String str )
• public boolean endsWith( String suffix )
• public boolean equals( Object anObject )
• public boolean equalsIgnoreCase( String anotherString )
• public int indexOf( int ch )
• public int indexOf( String str )
• public int length()
• public boolean startsWith( String prefix )
• public String substring( int beginIndex )
• public String substring( int beginIndex, int endIndex )
• public String toLowerCase()
• public String toUpperCase()
• public String trim() for meaning see
Java documentation
Another way to define a String
• Because Strings are so usful Java
provides an alternative method for
defining a String

String myString = “This is my string”;

• It can be used as a replacement for the


declaration using new String (…)
Java Keyboard Input with the
Scanner class
• A standard Java class
• We will use it to help with keyboard
input
• Part of JDK 1.5
import java.util.Scanner;
• The import tells Java to look for
Scanner methods
• A simple text scanner which parses
primitive types and strings
• Uses a delimiter pattern of
whitespace to identify tokens
Example Program 1
import java.util.Scanner;

public class Example1 {


public static void main (String [] args) {
Scanner myScanner =
new Scanner( System.in );
String aLine = myScanner.nextLine();
System.out.println( aLine);
}
}
Example Program 1
import java.util.Scanner;
// Tells Java to look for the Scanner class

Scanner myScanner =
new Scanner( System.in );
// Declares a Scanner object called myScanner

String aLine = myScanner.nextLine();


// nextLine() is a method of the Scanner class
// it reads a line of text from the keyboard.
• Could the user include digits like 123 in
the input characters?
– Yes. They are characters just like any
other
• Is data from the keyboard always only
characters?
– Yes. (Although frequently those characters
are converted to a numeric type after they
have been read in.)
Numeric Input
• Can a string of digits from the keyboard
be converted into an int type?
– The nextInt() method of a Scanner object
reads in a string of digits (characters)
– and converts them into an int type.
– The Scanner object reads the characters
one by one until it has collected those that
are used for one integer.
– Then it converts them into numeric data,
and stores that into an int variable
Example Program 2
import java.util.Scanner;

public class Example2 {


public static void main (String [] args) {
Scanner myScanner =
new Scanner( System.in );
int anInt = myScanner.nextInt();
System.out.println( anInt);
}
}
Exercise
• Will nextInt() work with the following?
1234
-1234
+1234
1234 5678
1234.0
rats
What happened when you tried
to enter rats
• If the next group of characters cannot
be converted, Java throws an Exception
and stops your program.
• An Exception object contains
information about what went wrong in a
program.
– Industrial-strength programs may examine
the exception and try to fix the problem.
– Our programs (for now) will just stop.
Other Scanner Methods
• The Scanner class provides a set of
useful methods that enable us to enter
data via the keyboard.
– these are listed on the next slide
• The most complex one is for values of
type char
– we will forget these for the moment
Some Scanner Methods
To read this Use this

A number with no decimal nextInt();


point
A number with a decimal nextDouble();
point
A word ending in a blank next();
space
A line ( or what remains nextLine();
of the line)
A single character findInLine(“.”).charAT(0);
Example Program 3
import java.util.Scanner;

public class Example3 {


public static void main (String [] args) {
Scanner myScanner =
new Scanner( System.in );
int anInt = myScanner.nextInt();
double aDouble = myScanner.nextDouble();
System.out.println( “The int was “+anInt);
System.out.println( “The double was “+aDouble);
}
}
Example 4
import java.util.Scanner;
public class AddTwo {
public static void main (String[] args) {
Scanner scan = new Scanner( System.in );
int first, second, sum ;
System.out.println("Enter first integer:");
first = scan.nextInt();
System.out.println("Enter second integer:");
second = scan.nextInt();
sum = first + second;
System.out.println("The sum of " + first + " plus " + second
+" is " + sum );
}
}
Style Note
• The previous examples have not been
very user friendly
– they did not prompt for input
• Any program expecting input from the
keyboard should be written so it asks
the user for input
• Example:
System.out.print (“Please enter price : “);
price = myScanner.nextDouble();
Exercise for out of class time:
• The total cost of an item is the basic cost
plus tax.
• The tax is calculated as a percentage of the
basic cost:
– e.g. if basic cost is £25 and the tax is 15% then
the total cost is 25 + 25 * 15 /100
• Write a program that has two inputs (using
the scanner class): basicCost and tax and
which will output the total cost to the screen.
CPR3013 Programming
Fundamentals
Algorithm Design Using
Flowchart
What is Flowchart?
• A flowchart is a diagram that depicts
the “flow” of a program.
• The figure shown here is a flowchart
for the pay-calculating program.
START

Flowchart Display message “How


many hours did you
work?”

Read Hours

Display message “How


much do you get paid
per hour?”

Read PayRate

Multiply Hours by
PayRate. Store result
in GrossPay.

Display GrossPay

END
Basic Flowchart START Terminal

Symbols
Display message
“How many
hours did you
work?”

• Terminals Read Hours

– represented by Display message

rounded rectangles “How much do


you get paid per

– indicate a starting or
hour?”

ending point Read PayRate

Multiply Hours by
PayRate. Store
START result in GrossPay.

Display
GrossPay

END Terminal
END
4
Basic Flowchart START

Symbols Display
message “How
many hours did
you work?”

• Input/Output Read Hours

Operations Display message

– represented by
“How much do you Input/Output
get paid per
hour?” Operation
parallelograms
– indicate an input or Read PayRate

output operation Multiply Hours


by PayRate.
Store result in
Display message GrossPay.

“How many
Read Hours Display
hours did you GrossPay

work?”
END
5
Basic Flowchart START

Symbols Display
message “How
many hours did
you work?”

• Processes Read Hours

– represented by Display message

rectangles
“How much do
you get paid per
hour?”
– indicates a process
such as a mathematical Read PayRate

computation or variable
assignment
Multiply Hours
by PayRate.
Process Store result in
GrossPay.
Multiply Hours
by PayRate. Display
GrossPay
Store result in
GrossPay. END
6
Four Flowchart Structures
• Sequence
• Decision
• Repetition
• Case

7
Sequence Structure
• A series of actions are performed in sequence
• The pay-calculating example was a sequence
flowchart.

8
Decision Structure
• The flowchart segment below shows a decision
structure with only one action to perform. It is
expressed as an if statement in Java code.

Flowchart Java Code

NO YES if (x < y)
x < y? a = x * 2;

Calculate a
as x times 2.

9
Decision Structure
• The flowchart segment below shows how a decision
structure is expressed in Java as an if/else
statement.

Flowchart Java Code

NO YES if (x < y)
x < y? a = x * 2;
else
Calculate a Calculate a a = x + y;
as x plus y. as x times 2.

10
Repetition Structure
• The flowchart segment below shows a repetition
structure expressed in Java as a while loop.

Flowchart Java Code

while (x < y)

YES x++;
x < y? Add 1 to
x

11
Controlling a Repetition
Structure
• The action performed by a repetition structure must
eventually cause the loop to terminate. Otherwise, an
infinite loop is created.
• In this flowchart segment, x is never changed. Once
the loop starts, it will never end.
• QUESTION: How can this
flowchart be modified so
it is no longer an infinite YES
x < y? Display x
loop?

12
Controlling a Repetition
Structure
• ANSWER: By adding an action within the repetition
that changes the value of x.

YES
x < y? Display x Add 1 to x

13
Case Structure

If years_employed = If years_employed =
2, bonus is set to 200 3, bonus is set to 400
If years_employed = If years_employed is
CASE
1, bonus is set to 100 years_employed any other value,
bonus is set to 800

1 2 3 Other

bonus = 100 bonus = 200 bonus = 400 bonus = 800

14
Connectors

•The “A” connector


A
indicates that the second START

flowchart segment begins


where the first segment
ends.

END
A

15
Modules

START
•The position of the module
symbol indicates the point the Read Input.
module is executed.
•A separate flowchart can be Call
calc_pay
constructed for the module. function.

Display
results.

END

16
Combining Structures
• This flowchart segment
shows two decision
structures combined. NO YES
x > min?

Display “x is outside NO YES


the limits.”
x < max?

Display “x is outside Display “x is


the limits.” within limits.”

17
Review

• What do each of the following


symbols represent?

(Answer on next slide)


18
Answer

• What do each of the following


symbols represent?
Decision
Terminal

Input/Output
Operation Connector

Process Module

19
Exercise 1
• Draw a flowchart based on the following
algorithm:
1 Start
2 Get the temperature in Fahrenheit
3 Compute the temperature in Kelvin using the
formula

 T −32 
TK =  F  + 273.15
 1.8 

4 Show the temperature in Kelvin


5 Stop
Answer
Start

Get TF

 T −32 
TK =  F  + 273.15
 1.8 

Show TK

Stop

21
Exercise 2
• Draw the flowchart for the following
algorithm:
1. Start
2. Get one number in the set
3. Count the numbers as it is obtained
4. If there are still numbers to be obtained,
go back to step 2.
5. Sum the numbers in the set
6. Divide the sum by the number of numbers
in the set to get the average
7. Show the sum and the average
8. Stop
Answer

Start

Calculate mean
Get number

Show sum
Count number Calculate sum and mean

Yes Any more No Stop


number?

23
Exercise 3
• Draw the 1.
2.
Start
Get h
flowchart for 3.
4.
If h < 11000 then
T ← 288.15 – 6.5*h*10-3
the following 5. Else if h < 20000 then
T ← 216.15
algorithm:
6.
7. Else if h < 32000 then
8. T ← 216.15 + *h*10-3
9. Else if h < 47000 then
10. T ← 228.65 + 2.8*h*10-3
11. Else if h < 51000 then
12. T ← 270.65
13. Else if h < 71000 then
14. T ← 270.65 – 2.8*h*10-3
15. Else T ← 214.65 + 2*h*10-3
16. Endif
17. Show h and T
18. Stop
Answer
Start

Get
altitude h

Yes
h < 11000? T ← 288.15 – 6.5*h*10-3

No
Yes
h < 20000? T ← 216.65

No
Yes
h < 32000? T ← 216.65 + h*10-3

No
B
A
Answer

h < 47000? T ← 228.65 + 2.8*h*10-3 B

h < 51000? T ← 270.65 Show h


and T

h < 71000? T ← 270.65 - 2.8*h*10-3 Stop

T ← 214.65 - 2*h*10-3
CPR3013 Programming
Fundamentals
Algorithm Design Using
Selection Construct
Defining Table
Input Processing Output

integer_1 Prompt for integers sum

integer_2 Get integers difference

Calculate sum, difference, product, product


quotient

Display results quotient


Solution Algorithm
Desk Checking
First data set Second data set
integer_1 20 100
integer_2 2 0

First data set Second data set


sum 22 100
difference 18 100
product 40 0
quotient 10 0
Desk Checking
Statement integer_1 integer_2 sum difference product quotient
number

First pass
1, 2 20 2
3 22
4 18
5 40
6 10
7, 8, 9, 10 display display display display

Second pass
1, 2 100 0
3 100
4 100
5 0
6 0
7, 8, 9, 10 display display display message
CPR3013 Programming
Fundamentals
Algorithm Design Using
Selection Construct
The selection control
structure
• The condition in the IF statement is based on a
comparison of two items and it is expressed with
the following relational operations:
– < less than
– > greater than
– = equals to
– <= less than or equal to
– >= greater than on equal to
– <> not equal to
The selection control
structure
• There are a number of variation of the
selection structure as follows:
1. Simple selection (simple IF statement)
2. Simple selection with null false branch
(null ELSE statement)
3. Combined selection (combined IF
statement)
4. Nested selection (nested IF statement)
The selection control
structure
1. Simple selection (simple IF statement)
– Simple selection occurs when a choice is
made between two alternate paths
depending on the result of a condition
being true or false
– Keywords: IF, THEN, ELSE, ENDIF
The selection control
structure
– Example:
IF account_balance < $300 THEN
service_change = $5.00
ELSE
service_charge = $2.00
ENDIF
The selection control
structure
2. Simple selection with null false branch
(null ELSE statement)
– The null ELSE structure is a variation of
the simple IF structure
– It is used when a task is performed only
when a particular condition is true
– No processing will take place if condition
is false
The selection control
structure
– Example
IF student_attendance = part_time THEN
add 1 to part_time_count
ENDIF
– In this case the part_time_count will be
altered only if he student’s attendance
pattern is part-time
The selection control
structure
3. Combined selection (combined IF statement)
– IF statement with AND or OR connector
– Example IF, AND connector
IF student_attendance = part_time
AND student_gender = female THEN
add 1 to female_part_time_count
ENDIF
– This example, student record will undergo two
test. Only those students who are female and
who attend part-time will be selected;
counter go up
– If either condition is to be found to be false,
the counter will not change
The selection control
structure
– Example IF, OR connector
IF student_attendance = part_time
OR student_gender = female THEN
add 1 to female_part_time_count
ENDIF
– Counter will only increase if
• The student is part-time regardless of gender
• The student is female regardless of attendance
pattern
The selection control
structure
– More than two condition can be linked
together with the AND or OR operators.
IF (record_code = ’23’
OR update_code = delete)
AND account_balance = zero THEN
delete customer record
ENDIF
– Remark → parentheses must be used to
avoid ambiguity
The selection control
structure
– The NOT operator can be used for the
logical negation of a condition
IF NOT (record_code = ’23’) THEN
update customer record
ENDIF
– Note that the AND and OR operators can
also be used with the NOT operator, but
great care must be taken and parentheses
used to avoid ambiguity
The selection control
structure
4. Nested selection (nested if statement)
– Can be classified as
• Linear nested IF statements
• Non-linear nested IF statements
– Linear nested IF statement is used when
a field is being tested for various values
and a different action is to be taken for
each value
The selection control
structure
– It is called Linear due to each ELSE
immediately follows the IF condition to which it
corresponds
IF record_code = ‘A’ THEN
increment counter_A
ELSE
IF record_code = ‘B’ THEN
increment counter_B
ELSE
increment error_counter
ENDIF
ENDIF
– Note there are an equal number of IF, ELSE
and ENDIF and indentation makes it easier to
read and understand
Algorithm using selection
• Example that use the selection control
structure. The problem will be defined,
solution algorithm will be developed and
the algorithm will be manually tested
• Example: Design an algorithm that will
prompt a terminal operator for three
characters, accept those characters as
input, sort them into ascending
sequence and output them onto screen
Algorithm using selection
A. Defining the diagram
Input Processing Output
char_1 Prompt for characters char_1
char_2 Accept 3 characters char_2
char_3 Sort three characters char_3
Output three characters
Algorithm using selection
Read_three_characters
B. Solution 1 Prompt the operator for char_1, char_2, char_3
algorithm 2
3
Get char_1, char_2, char_3
IF char_1 > char_2 THEN
• Solution temp = char_1
algorithm char_1 = char_2
char_2 = temp
requires a ENDIF
series of IF 4 IF char_2
IF char_1 > char_3
> char_3 THENTHEN
statements to temp = char_2
char_2 = char_3
sort the three char_3 = temp
characters into ENDIF
ascending 5 IF char_1 > char_2 THEN
temp = char_1
sequence char_1 = char_2
char_2 = temp
ENDIF
6 Output to the screen char_1, char_2, char_3
END
Algorithm using selection
• Logic of the algorithm is concerned with the
sorting of the three characters into
alphabetic sequence
C. Desk checking
• Set of valid characters will be used to check
the algorithm; the characters k, b and g will be
used
Algorithm using selection
• Input data
Data Set
char_1 k
char_2 b
char_3 g

• Expected results
Data Set
char_1 b
char_2 g
char_3 k
Algorithm using selection
• Desk check table

Statement no char_1 char_2 char_3 temp

First pass

1,2 k b g

3 b k k

4 g k k

6 output output Output


Algorithm using selection
• Try to write the second pass for the
test inputs: z, s & a
Exercise
Design an algorithm that will receive two
integer items from a terminal operator,
and display to the screen their sum,
difference, product and quotient. Note
that the quotient calculation (first
integer divided by second integer) is only
to be performed if the second integer
does not equal zero.
Exercise
• Create a defining diagram
• Create a solution algorithm using
pseudocode
• Create a desk checking
CPR3013 Programming
Fundamentals
Two-way Decisions
• The windshield
wipers are
controlled with an
ON-OFF switch.
• The flowchart at
right shows how
this decision is
made.
Decisions
• It seems small, but in programming
complicated decisions are made of many
small decisions
• In Java such two way decisions are
implemented using an if statement.
Switch statements can also be used
however they are less flexible as they
only work with limited data types.
Program as a
flow chart
Example Program 1
import java.util.Scanner;
class NumberTester {
public static void main (String[] args) {
Scanner scan = new Scanner( System.in );
int num;
System.out.print("Enter an integer:");
num = scan.nextInt();
if ( num < 0 )
System.out.println("The number " + num + " is negative");
else
System.out.println("The number " + num + " is positive");
System.out.println("Good-bye for now");
}
}
Explanation
• The words if and else are markers that
divide the decision into two sections.
• The else divides the true branch from
the false branch.
• The if is followed by a question enclosed
in parentheses.
– The expression num < 0 asks if the value in
num is less than zero.
explanation
• The if statment always asks a question (often about a
variable.)
• If the answer is true only the true-branch is
executed.
• If the answer is false only the false-branch is
executed.
• No matter which branch is chosen, execution
continues with the statement after the false-branch.
• If you omit the else statement then there is no false
branch and the execution will continue after the if
statement. And the statement is classed as a single
block if statement.
Single-block if Statements

If the answer is true,


follow the line labeled true,
do the directions in the box
follow the line to "done".
If the answer is false
follow the line to "done".

No
else
Three-way Decisions
• An if statement makes only two-way
decisions.

How do you deal with the


case when you must
sometimes pick from more
than just two branches?
Example
• we want the program logic to distinguish
between positive numbers, zero,
negative numbers
Solution
• First divide the integers into two groups
(using a two-waydecision):
negative
zero and positive
• Then further further divide the second group
(by using another two-way decision):
negative
zero and positive:
neither
positive
Flow chart
Nested If statements
if ( num < 0 )
{
System.out.println("The number " + num + " is negative");
}
else
{
if ( num > 0 )
System.out.println("The number " + num + " is positive");
else
System.out.println("The number " + num + " is zero");
}
Several Choices
• Some times we need to make several separate
choices in a program.
• This can be accomplished by means of a
“chain” of if’s
• e.g.
if (first choice)
do first choice
else
if (second choice)
do second choice

Alternative solution
if ( num < 0 )
{
System.out.println("The number " + num + " is negative");
}
else if (num > 0)
{
System.out.println("The number " + num + " is positive");
}
else
{
System.out.println("The number " + num + " is zero");
}
Loops
• There are three main elements to
programming
– Sequence
– Selection (if statements)
– Iteration (loops)
• A loop allows us to repeat a block of
code a number of times.
While Loop
while (Condition is true)
{
Repeat these steps.
Do something which may cause the
condition be become false
}
A simple example
class CounterExample
{
public static void main(String args[]) Prime the loop for the
{ Initial logical test
int counter = 0;
while(counter < 5)
{
System.out.println("Count is " +
counter);
counter = counter + 1;
}
}
}

Alter variable which may


Cause the loop to end
A more challenging problem
• We need to be able to break an input string
into separate words.
• For the purposes of testing we will use a
string literal rather then user input.

• Breaking the string into words is needed so


that they can be individually passed to a spell
checker.
• For our purpose we only need to place each
word into a string and then output it to the
screen.
String Methods which may help
• String.charAt(index)
– Method returns a char which is being referenced
by the index. Note the index starts at zero for
the first character.
• String.length()
– This method returns an int. The value is the
character length of the string.
• Example
String mess = “hi there”;
mess.length() returns the value 8
mess.charAt(1) return the char ‘i’
Loop to print each char in turn
class CounterExample
{
public static void main(String args[])
{
String mess = “hi there”;
int index = 0;
while(index < mess.length())
{
System.out.println(mess.charAt(index)
+ “ “ + index);
index = index + 1;
}
}
}
Still not the solution we need
• To be able to print out individual words we
need to use conditional processing within the
loop.
• We need to identify when there is a delimiter
between words. This is usually a space but can
be a tab(\t) or newline(\n)
• If a delimiter is detected then the program
should output the string which it has built
from concatenating chars.
• Else the string should be further built using
the chars.
public static void main(String args[])
{
String mess = "hi there";
String word = ""; Logical or
int index = 0;
while(index < mess.length())
{
char charVal = mess.charAt(index);
if (charVal ==' ' || charVal == “\n".charAt(0) || charVal ==“\t".charAt(0))
{
System.out.println(word);
word = "";
}
else
{
word = word + charVal;
}
index = index + 1;
}
System.out.println(word);
}
The previous solution is messy
• Java provides methods which allow input to be
broken up. As programmers we don’t need to
reinvent the wheel, but rather use the
components which have been prewritten for
us.
• Last week we looked at the scanner class
which was able to tokenize a string being
imputed from the keyboard.
• Scanner class can also be used to process a
normal string.
Scanner Class Solution
import java.util.Scanner;
class ScannerExample
{

public static void main(String args[])


{
String mess = "hi there";
Scanner scanner = new Scanner(mess);

while(scanner.hasNext())
{
System.out.println(scanner.next());
}
}
}
CPR3013 Programming
Fundamentals
Algorithm Design Using
Iteration Construct
Repetition using the
DOWHILE structure
• Most programs require the same logic
to be repeated for several sets of data
• The most efficient way to deal with
this situation is to establish a looping
structure in the algorithm that will
cause the processing logic to be
repeated a number of times
Repetition using the
DOWHILE structure
• Three different ways that a set of
instructions can be repeated:
– At the beginning of the loop (leading
decision loop)
– At the end of the loop (trailing decision
loop)
– A counted number of times (counted loop)
Repetition using the
DOWHILE structure
• Leading decision loop
– DOWHILE construct is a leading decision
loop – that is the condition is tested
before any statements are executed.
– Format is:
DOWHILE condition p is true
statement block
ENDDO
Repetition using the
DOWHILE structure
– The following processing takes place:
1.Logical condition p is tested
2.If condition p is found to be true, the
statements within the statement block are
executed once. The delimiter ENDDO then
triggers a return of control to the retesting
of condition p
3.If condition p is still true, the statements
are executed again, and so the repetition
process continues until the condition is found
to be false
4.If condition p is found to be false, no
further processing takes place within this
loop
Repetition using the
DOWHILE structure
– There are two important consideration to
be aware of before designing a DOWHILE
loop
• Testing of the condition is at the beginning of
the loop
• The only way to terminate the loop is to render
the DOWHILE condition false
Repetition using the
DOWHILE structure
• Using DOWHILE to repeat a set of
instructions a known number of times
– When a set of instruction is repeated a
specific number of times, a counter can be
used in pseudocode, which is initialised
before the DOWHILE statement and
incremented just before the ENDDO
statement
Repetition using the
DOWHILE structure
• Using DOWHILE to repeat a set of
instruction an unknown number of
times
– When a trailer record or sentinel exists
• Special record or value placed at the end of
valid data to signify the end of that data
– When a trailer record or sentinel does
not exist
• End-of-file (EOF) marker is added when the
file is created as the last character in the
file
Repetition using the
REPEAT…UNTIL structure
• Trailing decision loop
– REPEAT…UNTIL structure is similar to the
DOWHILE structure (group of statements
are repeated in accordance with specific
condition)
– REPEAT…UNTIL structure tests condition
at the end of the loop
– This means that the statement within the
loop will be executed once before the
condition is tested
Repetition using the
REPEAT…UNTIL structure
– If the condition is false, the statement
will then be repeated UNTIL the
condition becomes true
– REPEAT…UNTIL is a trailing decision
loop (the statement are executed once
before the condition is tested)
– Two consideration to be aware of when
using REPEAT…UNTIL
• Loops are executed when the condition is
false
• This structure will always be executed at
least once
Counted repetition
• Counted loop
– Counted repetition occurs only once when
the exact number of loop iterations is
known in advance
– Simple keyword DO is use as follows:
DO loop_index = initial_value to final_value
statement block
ENDDO
Counted repetition

– The DO loop does more than repeat the


statement block.
1. Initialise the loop_index to the required
intial_value
2. Increment the loop_index by 1 for each
pass through the loop
3. Test the value of loop_index at the
beginning of each loop to ensure that it is
within the stated range of values
4. Terminate the loop when the loop_index
has exceeded the specified final_value
Counted repetition
– In other words, a counted repetition
construct will perform the initialising,
incrementing and testing of the loop
counter automatically
– It will also terminate the loop once the
require number of repetition has been
executed
Algorithm Design using
Iteration
• Based on the following problem
statement:

Every day, a weather station receives temperatures


expressed in degrees Fahrenheit. A program is to be
written that will accept each Fahrenheit temperature,
convert it to Celcius and display the converted
temperature to the screen. After temperatures have
been processed, the words ‘All temperature processed’
are to be displayed on the screen
Algorithm Design using
Iteration
• Defining diagram
Algorithm Design using
Iteration
• Solution algorithm
Algorithm Design using
Iteration
• Desk Checking
– Although the program will require records
to process properly, it is still only
necessary to check the algorithm at this
stage with two valid sets of data
Algorithm Design using
Iteration
• Input data

• Expected results
Algorithm Design using
Iteration
• Desk check table
Algorithm Design using
Iteration
• Design the algorithm for the following
problem statement:

A program is required to read and print a series


of names and exam scores for students enrolled
in a computing course. The class average is to be
computed and printed at the end of the report.
Scores can range from 0 to 100. The last record
contains a blank name and a score of 999 and is
not to be included in the calculations
CPR3013 Programming
Fundamentals
for Loop
More problems to solve
for Loop
• A convenient loop to use when the
number of iterations is known in
advance.
• More compact, and easier to
understand than a while loop
• It is possible to use either a for or a
while loop in many circumstances and
they are interchangeable.
Question
• What are the three types of loops?

counting loop
sentinel-controlled loop
result-controlled loop
Structure of a loop
1. A loop much be initialised
correctly.
2. A logical test must be
preformed to see whether to
enter the loop
3. The body of the loop must
change something so that the
loop will eventually terminate.
• A for loop allows all three
pieces of the loop to be placed
on one line, reducing the change
of programming errors.
Structure
for ( initialize ; test ; change )
loopBody

for ( int count = 0; count < 10; count++ )


System.out.print( count + " " );

Equivalent to

int count = 0;
while ( count < 10 )
{
System.out.print( count + " ");
count++ ;
}
Question
• What would the loop output?
int sum = 0;
for ( int x = 0; x < 6; x++ )
{
sum = sum + x ;
System.out.print( x+ " " );
}
System.out.println( “\nsum is: " + sum );
Activity
• rewrite the previous program to use a
while loop
int sum = 0;
int x = 0;
while (x < 6)
{
sum = sum + x ;
System.out.print( x+ " " );
x++;
}
System.out.println( “\nsum is: " + sum );
Omitting Parts of the for
Moving the loop count variable to before
the beginning of the loop

int x = 0;
for ( ; x < 6; x++ )
{
System.out.print( x+ " " );
}
Omitting Parts of the for
• Moving the incremented to the main
part of the loop body.

for (int x = 0; x < 6; )


{
System.out.print( x+ " " );
x++;
}
A for loop with the same
structure as a while loop

int x = 0
for ( ; x < 6; )
{
System.out.print( x+ " " );
x++;
}
Scope
• The scope of a variable is the span of
statements were it is valid to use.
• The scope of the variable is the block in
which it is defined.
{
int x = 0;
Scope of variable x
System.out.prinln(x);
}
System.out.prinln(x); Cannot find symbol
Variable Scope and the for loops
• x has the scope of the loop only. when the
condition x<6 is no longer met and the loop
exits the variable x can no longer be used. It
can only be referenced from within the loop.

for ( int x = 0; x < 6; x++ )


{ Scope of
sum = sum + x ; variable x
System.out.print( x+ " " );
}
System.out.println(x); Cannot find symbol
More on Scope
System.out.println(“Even numbers”);
for ( int j = 0; j < 25; j=j+2 )
System.out.print(j + “ “);

System.out.println(“\nOdd numbers”);
for ( int j = 1; j < 25; j=j+2 )
System.out.print(j + “ “);

Two separate variables called j, each has


the scope of their individual loops so they
do not interfere with one another.
Keep things local
int j = 0;
System.out.println(“Even numbers”);
for (j = 0; j < 25; j=j+2 )
System.out.print(j + “ “);

System.out.println(“\nOdd numbers”);
for (j = 1; j < 25; j=j+2 )
System.out.print(j + “ “);

In this case the scope of the variable j is all the code


shown. THIS IS NOT GOOD PRACTICE. Both loops are
controlled by a single variable which is defined else
were. They are a no longer independent. This has the
potential to cause programming errors.
Problem
• To calculate the mean value of random
numbers who's range is between 0 and 100.
These numbers are whole numbers.
• The user will provide the number of random
samples to be taken.
• The computer will then generate the random
samples and calculate their mean
• The result will be displayed to the screen.
Design - Start
• 1.1 – get the number of samples from
the user using JOptionPane.
• 1.2 Convert the string to an integer.
Design - Loop
• 2.1Initialise a variable to hold the sum
of the numbers.
• 2.2 Loop (until correct number of
samples)
• 2.2.1 generate the random number
• 2.2.2 add random number to sum
• 2.2.3 add one to the loop counter.
Design final
• 3.1 calculate mean
• 3.2 display the mean
A little on random numbers
• Math.random() provides a double as a
random number grater or equal 0 and
less then 1
• To get the range from 0 to 100 we need
to multiply the returned number by 101.
• If we have a value returned of 0.999
multiplying this by 100 would only give
up 99.
Write and test initial part
import javax.swing.JOptionPane;
class tt
{
public static void main (String[] args)
{
String input = JOptionPane.showInputDialog(null,
"how many random numbers?",
"random",
JOptionPane.DEFAULT_OPTION);
int loop = Integer.parseInt(input);
System.out.println(loop);
}
}
Incorporate a loop
for (int x = 0 ; x<loop ; x++)
{
System.out.println(loop - x);
}

Before adding any additional code


make sure the loop works as expected.
It is easy to make mistakes with the
number of iterations.
Testing
Random Code
for (int x = 0 ; x<loop ; x++)
{
int result = (int)(Math.random()*101);
System.out.println(result);
}
We need to test that the full range of
number is being generated i.e. from 0
to 100 but no numbers outside of the
valid range
Check the full range
A better way to test for ranged
values.
for (int x = 0 ; x<loop ; x++)
{
int result = (int)(Math.random()*101);
if ((result <=0) || (result >=100))
System.out.println(result);
}
The final piece
String input = JOptionPane.showInputDialog(null,
"how many random numbers?", "random",
JOptionPane.DEFAULT_OPTION);
int loop = Integer.parseInt(input);
double sum = 0;
for (int x = 0 ; x<loop ; x++)
{
sum = sum + (int)(Math.random()*101);
}
double mean = sum / loop;
System.out.println(“mean is “ + mean);
We need to test the mean
• In order to test that the mean value is being
calculated correctly we need to comment out
the random number generation and substitute
with a known value. This means that the mean
should equal this fixed number.
for (int x = 0 ; x<loop ; x++)
{
//sum = sum + (int)(Math.random()*101);
sum = sum + 20;
}
Results
Final Run
• We have build the program incrementally.
• Each step has been tested to make sure it
works before adding more complexity.
• As long as our original design was correct
the program should work as each piece of
code has been tested and proven.
• All we now need to do is test the whole
program and evaluate the outcome.
Summary of results
• Input: 1 Mean:98
• Input: 2 Mean:45.5
• Input: 6 Mean:58.33333
• Input: 25 Mean:54.75
• Input: 100 Mean:49.42
• Input: 500 Mean:49.91
• Input: 1000 Mean:49.335
• Input: 1000000 Mean:50.01808
• Input:1000000000 Mean 49.999523
Notes on (some) methods of
class String

Strings 1
Constructing Strings - recap

String newString = new String(stringLiteral);

String message = new String("Welcome to Java!");

Since strings are used frequently, Java provides a


shorthand notation for creating a string:

String message = "Welcome to Java!";

Strings 2
Finding the length of a string

Finding string length using the length() method


of the String class:

String message = "Welcome to Java";


message.length(); //(returns 15)

Strings 3
Retrieving an Individual Character in a
String
String message = "Welcome to Java";
•Use message.charAt(index)
- a method of the String class
•index starts from 0
•Do not use message[index]
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message W e l c o m e t o J a v a

message.charAt(0) message.length() is 15 message.charAt(14)

Strings 4
String Concatenation

String s1 = “Hello”;
String s2 = “World”;
String s3 = s1 + s2;
String s4 = s1.concat(s2); // method of class String

System.out.println(s3); // outputs HelloWorld


System.out.println(s4); // also outputs HelloWorld

Don’t forget the space! “ “

Strings 5
Extracting substrings - 1
public String substring(int beginIndex)

• Returns a new string that is a substring of this string.

• The substring begins with the character at the


specified index and extends to the end of this string.

Examples:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (empty string)

Strings 6
Extracting substrings - 2
public String substring(int beginIndex, int endIndex)

• Returns a new string that is a substring of this string.


• The substring
– begins at the specified index (beginIndex) and
– extends to the character at index (endIndex) - 1.
• The length of the substring is endIndex - beginIndex.
Examples:
"hamburger".substring(4, 8) returns "urge“
"smiles".substring(1, 5) returns "mile"

Strings 7
Extracting substrings - 3
String is an immutable class.
Values of String objects cannot be changed individually.

String s1 = "Welcome to Java";


String s2 = s1.substring(0, 7); //Welcome
String s3 = s1.substring(11); //Java
String s4 = s1.substring(0, 11) + "HTML"; //Welcome to HTML

Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message W e l c o m e t o J a v a

message.substring(0, 11) message.substring(11)


Strings 8
String Comparisons (1) – equals()

String s1 = new String ("Welcome");


String s2 = "Welcome";
System.out.println("s1 == s2 is " + (s1 == s2));
System.out.println("s1.equals(s2) is " + s1.equals(s2));

if (s1.equals(s2)) //true if s1 & s2 have same content


if (s1 == s2) // true if s1 & s2 have same reference

Strings 9
String Comparisons (2) – compareTo()
String s1 = "Welcome";
String s2 = "welcome";
s1.compareTo(s2)

• returns 0 if s1 is equal to s2
• returns a value less than 0 if s1 is lexographically < s2
• returns a value greater than 0 if s1 is lexographically > s2
• Actual value (for Strings) depends on the offset of the 1st two
distinct characters
• if s1 is “abc” & s2 “abg”, compareTo would return –4
• CAUTION – errors will occur if you use comparison operators
(such as >, <=, etc). You must use compareTo with strings.
• Also compareToIgnoreCase(String)
Strings 10
String Comparisons (3) – other methods
• str.equalsIgnoreCase() – ignores the case of the letters
when comparing
• str.startsWith(prefix) – check if string starts with ‘prefix’
• str.endsWith(suffix) check whether string ends with ‘suffix’

String s1 = "Hello”, s2 = "HELLO";


System.out.println("s1.equals(s2) is "
+ s1.equalsIgnoreCase(s2)); // true
System.out.println(s1.startsWith("Hel")); // true
System.out.println(s1.endsWith("O")); // false

Strings 11
String Conversions
•The contents of a string cannot be changed once the string is
created. But you can convert a string to a new string using the
following methods:
toLowerCase()
toUpperCase()
trim() – removes whitespace from both ends of a string
replace(‘a’,’e’)
replaceAll(“a”,”e”)
replaceFirst(“a”, “e”)

String n = new String(“Fred Flannagan");


String n1 = n.toLowerCase();
String n2 = new String(n.replace(‘a',’e'));

Strings 12
Finding character/substring position in a String
public int indexOf(int ch)
• Returns index of first occurrence of the specified
character/substring. Otherwise returns ‘-1’

"Welcome to Java!".indexOf('W')) returns 0.


"Welcome to Java!".indexOf('x')) returns -1. ‘not found’
"Welcome to Java!".indexOf("come")) returns 3.

public int indexOf(int ch, int fromIndex)


• Returns index of first occurrence of the specified
character/substring, starting the search at the specified index.

"Welcome to Java!".indexOf('o', 5)) returns 9.


"Welcome to Java!".indexOf("Java", 5)) returns 11.
"Welcome to Java!".indexOf("java", 5)) returns -1.
Also lastIndexOf – similar to above
Strings
Not found (case sensitive!)
13
Convert Character / Number to String
The String class provides several static valueOf methods for
converting a character, an array of characters, and numeric
values to strings.

These methods have the same name valueOf with different


argument types char, char[], double, long, int, and float.

For example, to convert a double value to a string, use


String.valueOf(5.44). The return value is string consists of
characters ‘5’, ‘.’, ‘4’ & ‘4’.

double d = 5.44;
String s = String.valueOf(d);
s.length(); // returns 4

Strings 14
CPR3013 Programming
Fundamentals
Simple Methods
Real Number Formatting
Lotto
Methods
public class Hello {
public static void main ( String [ ] args )
{
print( "Hello World!“ );
}
public static void print ( String output )
{
System.out.println( output );
}
}
Methods
• Methods are essential in the development of
systems.
• VERY Simple programs can be programmed
without methods.
• More complex software require methods as
they allow:
– Repeated operations to be placed in one section
of code, reducing code and complexity
– Problems to be decomposed into more
manageable pieces.
– Object orientation requires methods as part of
it’s structure
Method signatures
public class Hello {
public static void main ( String [ ] args )
{
print( “A Message” );
print( “ThreeTimes“,3 );
}
public static void print ( String output )
{
System.out.println( output );
}
public static void print ( String output, int times )
{
for (int x = 0 ; x < times ; x++)
System.out.println( output );
}
}
Method Signatures
• The name of the method and it’s list of formal
parameter makes the Method Signature.
public static void print ( String output )
Method Signature

print( “A Message” ,4);


Calls the print method with a string and an int.
• There are two print method defined. Only the second
matches the call to the method of String, Int.
public static void print ( String output )
public static void print ( String output, int times )
Formatting Real Numbers
• We often need to work with real
numbers but these are often less than
ideal to display to the user.

double d = 1.22222222222222d;
float f = 1.22222222222222f;
System.out.println("double :"+d);
System.out.println(" float :"+f);
Formatting
• Two method
– Simple calculation
– Use a pre-defined java class
• Method one
– Multiply the double by 10 or 100 or 1000…
– The multiplication is cast to an int.
– The int result is then divided by 10.0,
100.0, or 1000.0 producing a double as the
result
Formatting method one cont.
class DispNum
{
public static void main (String[] args)
{
double d1 = 1.88888888888888d;
double d2 = 1.8888888888888d;

d1 = ((int)(d1*10))/10.0;
d2 = ((int)(d2*100))/100.0;
System.out.println("d1 :"+d1);
System.out.println("d2 :"+d2);
}
}
Formatting method two
import java.text.NumberFormat;
import java.util.Locale;
class DispNum
{
public static void main (String[] args)
{
double d1 = 123.456789;
double d2 = 123;
double d3 = 10000000.8888888;
NumberFormat nf = NumberFormat.getInstance(Locale.UK);
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);

System.out.println("result d1: " + nf.format(d1));


System.out.println("result d2: " + nf.format(d2));
System.out.println("result d3: " + nf.format(d3));
}
}
Result from NumberFormat
• Rounding rather than
truncation occurs.
• Minimum fraction
digits force zeros to
be printed
• Thousands format is
also present.
• This method is
designed for financial
information
Lotto
• Problem,
– If you choose a set of numbers or fill out a
lotto ticket by selecting the numbers you
will pick numbers which others are more
likely to choose.
– If a true random set of numbers wins you
are more likely to be the only winner.
– Task to create a method which will pick
lottery numbers.
Lotto cont.
• Numbers are picked from a set of
possible numbers 1-n.
• The result is a set of numbers, i.e. no
repeated numbers, chosen from the
possible numbers
• The cardinality of the results set r is
less than or equal to n. r is a subset of n
Choosing a method Signature
public static void makeMeAWinner(int number, int available)

• Method takes two integers.


– The variable available represents the size of the
set for which numbers will be chosen. Possible
numbers are 1 – available
– The variable number is the number of uniqe
numbers which should be chosen from the possible
set.
Observations
• makeMeAWinner(int number, int available)

• A number can be chosen from the available


set by using the Random method we have
already used

• We need to provide a fixed number of


selected numbers, so a loop is needed to
control this
First Program
class Lotto
{
public static void main (String[] args)
{
makeMeAWinner(10,20);
}
public static void makeMeAWinner(int number ,int available)
{
for (int x=0; x< number ; x++)
{
int newNumber = (int)((Math.random()*available)+1);
System.out.println(newNumber);
}
}
}
Testing
• We fail to meet one of
the important criteria.
• The numbers are not a
set there are repeated
numbers.
• However the range
appears to be correct and
the number chosen also
seems to pass initial
testing
Further Observations
• We need to be able to store the numbers we
have chosen, so the list can be checked and
any duplicates rejected.
• A number of variables such as n1, n2, n2…
would not work as we do not know how many
we need!
• A string can be used to store the numbers.
A string can be checked to see if a substring
exists inside the string. So it can be used to
see if a number is being repeated!
Checking a String for a substring
class CkStr
{
public static void main (String[] args)
{
String str = "I wish it was summer!";

System.out.println(str.contains("ummer"));
System.out.println(str.contains("wass"));
}
}
Amended code
public static void makeMeAWinner(int number ,int available)
{
String chosen = "";
for (int x=0; x< number ; x++)
{
int newNumber = (int)((Math.random()*available)+1);
while (chosen.contains(newNumber+""))
{
newNumber = (int)((Math.random()*available)+1);
}
chosen = chosen + " " + newNumber;

System.out.println(newNumber);
}
}
Testing
• All appears to work
however there is a
problem which is only
seen with additional
testing.
• Using (19,20) the
program enters an
infinite loop. WHY?

• Observations:
• All numbers between 10 & 20 shown
• Numbers less than 10 are only in first
half of the output
Problem in the while loop
• Suppose number 18 is the first number
generated. It is placed in the chosen
String (results set)
• The next time round in the loop:
if either a 1 or an 8 is generated then it
will be rejected as a duplicate.
chosen.contains(“1”) will be true.
chosen.contains(“8”) will be true.
Solution
• Make sure that every number in the contains
string has a space either side of it.
• Orignial contains string would look this this
“10 11 14 6 8 5”
• We need to change by adding spaces.
“ 10 11 14 6 8 5 ”
• When we check for the presence of a number
we check that there are spaces surrounding
it.
Changes in red
public static void makeMeAWinner(int number ,int available)
{
String chosen = " ";
for (int x=0; x< number ; x++)
{
int newNumber = (int)((Math.random()*available)+1);
while (chosen.contains(" "+newNumber+" "))
{
newNumber = (int)((Math.random()*available)+1);
}
chosen = chosen + newNumber + " ";

System.out.println(newNumber);
}
}
Results
(18,20) (20,20)
Improvements
• Output the numbers in numerical sequence.
• The number have to be generated before we
can place then into a logical sequence.
Therefore this needs to be done as the last
part of the method.
• We have not looked at a sorting algorithm
(week12). However we can solve this with
techniques that have already covered.
• Any ideas????
Ordered Sequence
public static void makeMeAWinner(int number ,int available)
{
String chosen = " ";
for (int x=0; x< number ; x++)
{
int newNumber = (int)((Math.random()*available)+1);
while (chosen.contains(" "+newNumber+" "))
{
newNumber = (int)((Math.random()*available)+1);
}
chosen = chosen + newNumber + " ";
// System.out.println(newNumber);
}
for (int x=1; x<= available ; x++)
{
if (chosen.contains(" "+x+" "))
System.out.println(x);
}
}
Testing
(10,20) (20,20) (10,1000)
CPR3013 Programming
Fundamentals
Introduction to Arrays
Passing Arrays and other
object to and from methods
Question
If you needed to input 100 numbers to
work out the mean and standard
deviation. Would you create 100
variables to store this data.

This would make your program very


difficult to write understand and maintain
Arrays offer a simple solution!
Definition of an array
• An array is an object that is able to
store a list of values which are all of
the same type. It uses a contiguous
block of memory that is divided into a
number of Cells.
• The arrays can hold either Primitive or
Object data types. E.g. int or String
Example Array
myArray
• In this case we have an array
containing 6 cells or elements.
• The elements are all of type int 0 42
• Each element has a unique index 1 63
between 0 – 5.
2 5
• Element at index 1 is 63
• Element at index 5 is 41 3 70
• The name of the array is myArray. 4 65
To access a particular element of the
array we use myArray[index] 5 41
• System.out.println(myArray[2]);
• Would print the value 5. Index Value
Changing a value
myArray
• myArray[0] = 50; 0 42 0 50
1 63 1 63

• myArray[4] = 2 5 2 5
myArray[2] * 3; 3 70 3 70
4 65 4 15

• int x = 2 5 41 5 51

• myArray[x+3] += 10; Before After


Declaring an Array
• DataType[] ArrayName;
• This statement does not create an array it
contains a variable called ArrayName which is
a reference variable for an array which holds
the specified data type. See 1- next slide
• ArrayName = new DataType[length];
• This statement creates the array in memory,
of the specified length see 2- next slide. It
then updates the reference variable with the
memory location of the array see 3- next
slide.
Declaring an array part 2
memory

• int[] values; 0 0

Values Null reference 1 0


1 2 0
2
3 0
• values = new int[5]; 4 0
3

Values
Arrays specify the data type
• Primitive type examples
• int[] intArray = new int[10];
• char[] charArray = new char[20];
• double[] doubleArray = new double[10];

• Object type examples


• String[] strArray = new String[50];
• Scanner[] ScrObj = new Scanner[10];
For loops to index the array
int[] myarray;
• If an array has n myarray = new int[10];
elements the valid for (int x = 0 ;
index values are 0 to
n-1 x < myarray.length ;
• The array can tell us x++ )
how big it is by {
accessing a special myarray[x] =
array variable called (int)(Math.random()*10);
length. We access }
this by
arrayname.length for (int x = 0 ;
• We can use this x < myarray.length ;
variable in our for
x++ )
loop to determine
when the loop should {
end. System.out.println(myarray[x]);
}
Results
Passing an array to a method
class passArray
{
public static void main(String[] args)
{
int[] intarr = new int[20];
for (int x = 0 ; x < intarr.length ; x++)
intarr[x] = (int)(Math.random()*100);
printArray(intarr);
}
public static void printArray(int[] arr)
{
for (int x = 0 ; x < arr.length ; x++)
System.out.println(arr[x]);
}
}
Results
Notes
• Passing an array to a method.
– int[] intarr = new int[20]; The main
method declares an array which will be passed to
the printArray method.
– The main method invokes the method by passing
value in the array reference variable to the
method. printArray(intarr).
– Note this is intarr not intarr[] or intarr[x]
– The method printArray(int[] arr) Creates an array
reference variable called arr which will hold the
memory location of the array being passed to the
method.
memory
Visual explanation Step2

0 74
• Main
Step1
method Step1 1 84
int[] intarr; intarr 2 49
Step3 Step2 3 18
intarr = new int[20]; intarr
4 46
Step3
printArray(intarr); 5 4
6 8
Step4 7 82
• PrintArray(int[] arr) 8 12
The reference value in intarr is arr 9 43
copied into arr. They are two Step4
separate variables but are aliases
for the same object in memory
Returning an array from a method
class ReturnArray
{
public static void main(String[] args)
{
int size = 30;
int[] intarr = rndArray(size);
for (int x = 0 ; x < intarr.length ; x++)
System.out.println(intarr[x]);
}
public static int[] rndArray(int arrSize)
{
int[] arr = new int[arrSize];
for (int x = 0 ; x < arr.length ; x++)
arr[x] = (int)(Math.random()*100);
return arr;
}
}
results
Notes on returning arrays
• The return type is an array in this example an
int array, observe the return type of int[]
• The array is created in the method
rndArray(int) and the values are initialised.
This creates an int array reference variable
arr and creates the array in memory.
• The method rndArray passes back the value
of the array reference, with return arr;
• In the main method the reference which is
passed back from rndArray is placed into the
int array reference variable intarr
Passing by Reference not Value
• Primitive data types are passed by value.
The value in one variable is copied into the
memory location of another variable. They are
separate variable changing the value of one
does not affect the other.
• Objects are passed via their reference.
Essentially the memory reference value is
copied from one reference variable to
another. The two variable are separate BUT
they are aliases for the same object in
memory. They both point to the same object!
Example passing by value and reference
class ByValueAndRef
{
public static void main(String[] args)
{
int intOrd = 10;
int[] intArr = {10};
System.out.println("Ordinary Int :" + intOrd);
System.out.println("Array object :" + intArr[0]);
multByTen(intOrd,intArr);
System.out.println("Ordinary Int :" + intOrd);
System.out.println("Array object :" + intArr[0]);
}
public static void multByTen(int x,int[] y)
{
x *=10;
y[0] *=10;
}
}
Results
Does not work with
every object type
• Immutable objects are objects whose data cannot
change after the object is created.
• String is an immutable data type which you have
already used.
String str = “a string cannot “;
str = str + “be changed”;
• The first line creates a string in memory and places
reference to the object in the variable str
• The concatenation does not alter the string object
but rather creates a new object of type and changes
the reference variable str to point to the new object
• Java garbage collection will free the memory which
the original unreferenced string object uses.
Visual explanation
memory

String str = new String (“a string cannot”);


String object 1
str a string cannot

str = str + “be changed”;


x String object 2
a string cannot
str be changed

str = str.toUppercase();
x String object 3
A STRING CANNOT
str BE CHANGED

All three string will reside in memory however the str


only reference the last string Object. Java will free
the memory of used by the unreferenced objects.
Passing immutable objects
class ObjStringPassing
{
public static void main(String[] args)
{
String str = "strings cannot";
System.out.println(str);
changeString(str);
System.out.println(str);

}
public static void changeString(String str)
{
str = str + “ be changed";
System.out.println("called method: " +str);
}
}
Results
Mutable
• You should compile the following program
outside of class and check it works as
expected.
• Add a String, in addition to the StringBuffer
and check the results are as expected.
• Mutable objects can be changed by the
method they are pass to, so they are not
isolated in the same way as primitive and
immutable types.
StringBuffer Code
class StrStrBuff
{
public static void main(String[] args)
{
StringBuffer strb = null;
strb = new StringBuffer("String Buffer Object");
System.out.println(strb);
changeValue(strb);
System.out.println(strb);
}
public static void changeValue(StringBuffer strb)
{
strb.append("changed");
System.out.println(strb);
}
}
String Array (objects)
String[] planets = new String(6);
Planets[0]=“Mercury”;
Planets[1]=“Venus”; String Object
Planets[2]=“Earth”;
0 Mercury
1 Venus
2 Earth
3
Essentially an array of
4 objects is a list of object
references. Which will
planets 5 either point to an object
or is a NULL
Problem: Letter frequency
• The Caesar cipher which we discussed in
previous weeks are knows as mono alphabetic
substitution ciphers.
• This type of cipher suffers from a problem
that not all letter in the English Language
have the same chance of occurring, some
letters are much more common than others.
• By analysis the letter frequency it is possible
the cryptoanalyse all mono alphabetic ciphers.
All this is based on one
hypothesis
• The letter frequency of English is the same no
matter the source (Shakespeare, dickens, Beatrix
Potter, translated from another language)

• We need to construct a method which will take a


frequency array (type int) which represents all (26
letters).

• It will also accept a string, used to update the


frequencies.

• Each letter in the string will be used to update the


character frequency.
Freq Method
public static void freq(String str, int[] countLetter)
{
str = str.toLowerCase();
for (int x = 0 ; x < str.length(); x++)
{
int letterIndex = str.charAt(x)-'a';
if ((letterIndex>= 0) && (letterIndex<=25))
{
countLetter[letterIndex]++;
}
}
}
Main Method
public static void main (String [] args)
{
int[] countLetter = new int[26];
String str = "this is a simple test sentence";

freq(str,countLetter);

for (int x = 0 ; x < 26; x++)


System.out.println(((char)(x+'a'))+ " count :"
+countLetter[x]);
}
results
Additional changes
• File processing so that free books from
Project Gutenberg can be used.
• This involves the scanner class however
file processing is covered in semester
two, so it will not be covered here.
• To make the results comparative the
percentage rather than frequency needs
to be calculated.
14

12

10

0
a b c d e f g h i j k l m n o p q r s t u v w x y z

Ulysses-James Joyce 7.9 1.8 2.5 4.1 12 2.3 2.3 6.1 6.9 0.2 1 4.6 2.7 6.8 7.7 1.9 0.1 5.9 6.5 8.5 2.8 0.8 2.2 0.1 2.1 0.1
Homer-The Iliad 7.5 1.4 2.4 4.6 13 2.4 2.2 6.8 6.5 0.2 0.6 4.2 2.3 6.5 7.2 1.8 0.1 6.7 7.5 8.7 2.8 1 2 0.2 1.6 0.1
Charles Dickens The Pickw ick Papers 7.9 1.4 2.7 4.6 12 2.1 2 5.9 7.2 0.2 1.2 4.2 3 6.9 7.2 2.1 0.1 6.2 6.2 8.6 2.7 0.9 2.5 0.2 2 0.1
Charles Dickens A CHRISTMAS CAROL 7.6 1.6 2.7 4.5 12 2.1 2.5 6.5 6.9 0.1 0.9 3.7 2.4 6.6 8.1 1.9 0.1 6 6.4 9.1 2.8 0.8 2.5 0.1 1.9 0.1
Shakespeare JULIUS CAESAR 8 1.9 2.8 3.8 11 1.9 1.4 5.7 6.9 0 0.8 4.2 2.8 6.1 7.9 1.4 0 6.3 7.8 8.8 4.4 1 2.2 0.1 2.4 0.1
Beatrix Potter Stories 7.9 2.1 2.4 4.9 12 1.9 2.3 6.4 6.5 0.2 1.2 4.2 2.7 6.7 7.1 2.4 0.1 5.2 5.8 9.4 3 0.7 2.4 0.1 2 0
Files and File IO

1
Input and Output Streams

• Input is data going into a program.


• Output is data flowing out of a program.
• IO is frequently done using IO streams.
• A stream is a sequence of data flowing from a source
to a destination.
• IO streams can be connected to a wide variety of
data sources and destinations.

2
IO Streams
• The core Java language does not have any IO
methods.

• For a program to do IO, it must import an IO package:

java.io .*;

• Data for a program may come from several sources.

• Data created by a program may be sent to several


destinations.

3
IO Sources
• An array of bytes
• A String object
• A file
– text
– binary
• other sources, e.g. an internet connection

4
The File Class
• The File class is used to
– obtain file properties
– to create files
– delete files
– rename files.
• The File class is intended to deal with most of
the machine dependent complexities of files &
pathnames in a machine-independent
fashion.

5
Note
• Constructing a File instance does not create a
file on the machine.
• You can create a File instance for any filename
regardless of whether it exists or not.
• Class API
– http://download.oracle.com/javase/6/docs/api/ja
va/io/File.html#File(java.lang.String)

6
The File Class Constructors
• There are several different constructors.
• We are interested in the one with a String parameter.
• The filename is a string.
• Note of file names:
– Do not use absolute filenames in your program as they may
not be platform independent.
– You should use a file name relative to the current directory.
– For example, you may create a File object using
new File(“Welcome.java”)
for the file Welcome.java in the current directory.

Week 8 7
Character Streams and Byte Streams
• Character streams are intended exclusively for
character data.

• Character streams are optimised for character data


and perform some other useful character oriented
tasks.

• Byte streams are intended for general purpose input


and output.

• Fundamentally all data consist of patterns of bits


grouped into 8-bit bytes.

8
Types of Streams

• A stream object may be:


– An input stream or an output stream;
– A character-oriented stream or a byte-oriented stream;

And may be connected to a variety of sources or destinations

• Java uses the same data formats for all computers

9
Hierarchy for the java.io Package

dotted clouds
are
abstract
classes.

10
Readers and Writers

• Readers & Writers deal with character streams.

• These are abstract classes.

• A program must use classes derived from them.

– For example, a BufferedReader is a type of


Reader

11
Java File I/O
• In order to perform I/O you need to create
objects using appropriate Java I/O classes.

• These objects contain the methods for


reading/writing data from/to a file.

• This section introduces how to read/write


strings & numeric values from/to text file
using the Scanner & PrintWriter classes.

12
file processing pattern
• Link to a file
– declare a File object
– pass it to a stream object
• Process the data
while (not end of data)
process data
• Close the file
– close()

13
PrintWriter
• The java.io.PrintWriter class can be used to
write data to a text file.
• Two constructors of interest:
PrintWriter(String filename)
PrintWriter(File file)

If the file already exists, the existing content of


the file will be discarded.
14
PrintWriter
• Both throw FileNotFoundException.
– If the given file object does not denote an existing,
writable regular file and a new regular file of that
name cannot be created.
– if some other error occurs while opening or creating
the file.
• A checked exception so must do something.

15
Example
import java.io.*;
public class WriteData
{
private File file;
private PrintWriter output;

public WriteData(String fileName)


{
file = new File(fileName);
if (file.exists())
{
throw new IllegalStateException ( fileName + " already exists");
}
} 16
public void makeLink() throws FileNotFoundException
{
output = new PrintWriter(file);
}

public void writeToFile()


{
output.print("Roger Allers ");
spaces before 2nd “s
output.println(90);
output.print(“Rob Minkoff ");
output.println(85);
}
public void closeLink()
{
output.close();
}
} // end WriteData
17
Closing a file
• The close() method should always be used when a
program is done with a file.
– If a file is not closed, the program might end before the
operating system has finished writing data to the file.
– The data written to the file might be lost!

• Or it might not! Depends on how busy the operating


system is. This is a notorious computer bug.
• It can be very frustrating, because sometimes a
buggy program will work correctly, and sometimes
not.

18
Reading from a file
• Java provides many classes to help read text
from a file
– see slide for Readers
• We will use the Scanner class
• See:
http://download.oracle.com/javase/6/docs/api/java
/util/Scanner.html

19
Constructors for Scanner
• Many but one we are interested in is:
public Scanner(File source) throws FileNotFoundException

• To create a Scanner to read data from a file


– create an instance of the File using the constructor
new File(filename)

– use new Scanner(File) to create a Scanner for the file.

• Invoking the constructor new Scanner(File) may throw a


FileNotFoundException.
20
Some Scanner Methods
To read this Use this

A number with no nextInt();


decimal point
A number with a decimal nextDouble();
point
A word ending in a blank next();
space
A line ( or what remains nextLine();
of the line)
A boolean value, i.e. true nextBoolean();
or false
More Scanner methods
• Have preconditions: token of form specified by
method used, otherwise fails.
• To verify these preconditions use:
– hasNextBoolean()
– hasNextInt()
– hasNextDouble()
– hasNext()
• close()
22
import java.util.*;
import java.io.*; Example
public class ReadData
{
private File file;
private Scanner input;
/**Constructor for objects of class ReadData */
public ReadData(String fileName)
{ file = new File(fileName);
if (!file.exists())
{
throw new IllegalStateException( fileName + " does not exist
exists");
}
} 23
public void makeLink() throws FileNotFoundException{
input = new Scanner(file);
}
public String readFromFile(){
String firstName = input.next();
String lastName = input.next();
int score = input.nextInt();
return firstName + " " + lastName + " " + score;
}
public void closeLink() {
input.close();
}
}
24
Writing and Reading Data in
Driver
import java.util.*;

public class Driver


{
public static void main(String[] args){
String fileName;
Scanner keyboard = new Scanner(System.in);

System.out.println("Give the name of file to save: ");


fileName = keyboard.next();

25
try{
WriteData wd = new WriteData(fileName);
wd.makeLink();
wd.writeToFile();
wd.closeLink();
ReadData rd = new ReadData(fileName);
rd.makeLink();
System.out.println(rd.readFromFile());
System.out.println(rd.readFromFile());
rd.closeLink();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
} 26
Dealing with end of file
• Problem is attempting to read beyond the end
of the data in the file
• Can use Scanner has ‘has...’ methods to solve
problem
• e.g.
if ( input.hasNext() )
read data
else
do not read data
27
Typical file reading pattern
while ( input.hasNext() )
{
// read from file
// process data
}

28
Typical file reading pattern
public String readFromFile2()
{ String output="";
while ( input.hasNext() )
{
String firstName = input.next();
String lastName = input.next();
int score = input.nextInt();
output += firstName + " " + lastName + " " + score + "\n";

}
return output;
}
29
try{
In driver
WriteData wd = new WriteData(fileName);
wd.makeLink();
wd.writeToFile();
wd.closeLink();
ReadData rd = new ReadData(fileName);
rd.makeLink();
System.out.println(rd.readFromFile2());
rd.closeLink();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
30
CPR3013 Programming
Fundamentals
Algorithm Design
The Structure Theorem
• There are three basic control
structures
1. Sequence
2. Selection
3. Repetition
The Structure Theorem
1. Sequence
– Straightforward execution of one
processing step after another
– Represents the first four basic computer
operations
1. Receive information
2. Put out information
3. Perform arithmetic
4. Assign values
The Structure Theorem
– A typical sequence statement in an algorithm might
read:
Add 1 to pageCount
Print heading line1
Print heading line2
Set lineCount to zero
Read customer record

– These instructions illustrate the sequence control


structure as a straightforward list of steps
written one after the other, in a top-to-bottom
fashion
The Structure Theorem
2. Selection
– Presentation of a condition and the choice
between two actions, the choice
depending on whether the condition is
true or false
– Represents the decision-making abilities
of the computer
– Illustrates the fifth basic computer
operation – compare two variables and
select one of two alternate actions
The Structure Theorem
– In pseudocode, selection is represented by the
keywords IF, THEN, ELSE and ENDIF
IF condition p is true THEN
statement(s) in true case
ELSE
statement(s) in false case
ENDIF
– If condition p is true, then the statement in true
case will be executed, and the statement in the
false case will be skipped (vice versa)
The Structure Theorem
3. Repetition
– Presentation of a set of instruction to be
performed repeatedly, as long as the
condition is true
– Block statement is executed again and
again until a terminating condition occurs
– Illustrates the sixth basic computer
operation – to repeat a group of actions.
The Structure Theorem
• Written in pseudocode as:
DOWHILE condition p is true
statement block
ENDDO
• DOWHILE is a leading decision loop – condition is
tested before any statements are executed
• ENDDO triggers a return of control to the retesting
of the condition
• Condition is true, statements are repeated until
condition is found false
Developing an algorithm
Developing an algorithm
• First step in the development of a
computer program is defining the
problem
• Problem should be divided into three
separate components:
1. Input: a list of source data provided to
the problem
2. Output: a list of the outputs required
3. Processing: a list of actions needed to
produce the required outputs
Developing an algorithm
• Refer to the following problem:

“A program is required to read three


numbers, add them together and print
their total”
Developing an algorithm
• First, underline the nouns and
adjectives used in the specification

“A program is required to read three


numbers, add them together and print
their total”
Developing an algorithm
• It is helpful to write down these first
two components in a simple diagram,
called defining diagram.
Developing an algorithm
• Second underline (in a different colors)
the verbs and adverbs used in the
specification

“A program is required to read three


numbers, add them together and print
their total”
Developing an algorithm
• Writing down each processing verbs to
our defining diagram
Developing an algorithm
• When it comes to writing down the
processing steps in an algorithm, you
should use words that describe the
work to be done in terms of single
specific tasks or function. For example:

1.0 Read three numbers


2.0 Add numbers together
3.0 Print total number
Developing an algorithm:
Temperature Algorithm
• Try to define the following problem with
a defining diagram

“A program is required to prompt the terminal


operator for the maximum and minimum
temperature readings on a particular day,
accept those readings as integers, and calculate
and display to the screen the average
temperature, calculated by (maximum
temperature + minimum temperature) /2”
Developing an algorithm
• Second step is to design a solution
algorithm
• Reminder – if the algorithm is not
correct, the program will never be
correct
• It is important not to start coding until
necessary steps of defining the problem
and designing the solution algorithm
have been completed
Developing an algorithm
• Here is the sample solution algorithm
for the preceding example:
Developing an algorithm
• There are number of points to consider
in solution algorithm:
1. A name has been given to algorithm (self-
descriptive)
2. An END statement to indicate the
algorithm is complete
3. Indentation for all processing steps
Developing an algorithm
• Write an algorithm for the
Temperature algorithm with the
following defining diagram:
Developing an algorithm
• After a solution algorithm has been
established, the last step is it must be
tested for correctness
• It is necessary because most major
logic errors occur during the
development of the algorithm (not
detected then these errors can be
passed on to the program)
• Easier to detect errors in pseudocode
than in the corresponding program
Checking the solution
algorithm
• Steps in desk checking an algorithm
1. Choose simple input test cases that are valid
2. Establish the expected result for each test
case
3. Make a table on a piece of paper of the
relevant variable names within the algorithm
4. Walk the first test case through the
algorithm
5. Repeat the walk-through process using other
test data
6. Check the expected result established in
Step 2 matches the actual in Step 5
Developing an algorithm
• Choose two sets of input test data. The
three numbers selected will be 10, 20
and 30 for the first test case and 40,
41 and 42 for the second.
Developing an algorithm
• Establish the expected result for each
test case
Developing an algorithm
• Set up a table of relevant variable
names, and pass each test data set
through the solution algorithm,
statement by statement (This is called
white box testing). Line numbers have
been used to identify each statement
within the program
Developing an algorithm

• Check that the expected results


(60 & 123) match the actual results
Developing an algorithm
• Perform desk check for the
temperature algorithm:
SCHOOL OF ENGINEERING, COMPUTING
AND BUILT ENVIRONMENT

DEPARTMENT OF COMPUTING

BACHELOR OF COMPUTER SCIENCE (HONS) IN COMPUTER AND


NETWORK TECHNOLOGY
BACHELOR OF INFORMATION SYSTEMS (HONS)
BACHELOR OF COMPUTER SCIENCE (HONS)

PROGRAMMING FUNDAMENTALS (CPR3013)

FINAL EXAMINATION
SEPTEMBER 2018 SEMESTER

DURATION: 2 HOURS

TOTAL MARKS: 100

General Instructions:

1. All answers are to be written in black or blue ink on the answer booklet provided.
2. This examination consists of FOUR questions. Answer ALL questions.
3. This examination paper consists of TWO pages of questions.
4. Students caught copying, or having unauthorized printed materials, pieces of written materials,
or any form of action with intention to cheat and/or copy will be penalized.
CPR3013 Programming Fundamentals
Final Examination, September 2018 Semester: Set A

Answer ALL questions.

1. Ms. Blanchett owns 5 apartment buildings. Each building contains 10 apartments that she rent
out for RM 500 per month each. The program should output 12 payment coupons for each of
the 10 apartments in each of the 5 buildings. Each coupon should contain the building number
(1 through 5), the apartment number (1 through 10), the month (1 through 12), and the amount
of rent due.
(a) Design an algorithm by using flow chart for solving the problem as stated above. (12 marks)
(b) Write a complete Java program based on the algorithm you design in Question 1(a).
(10 marks)
[22 marks]

2. Bonus will be given to salespersons varies according to the productivity score of the particular
salesperson. The program should prompt the user to input the productivity score of a salesperson
and output the bonus amount until a sentinel amount of -99 is entered. The bonuses will be
distributed as follow:

• If the productivity score is 30 or less, the bonus is RM25.


• If the productivity score is 31 or more and less than 80, the bonus is RM50.
• If the productivity score is 80 or more and less than 200, the bonus is RM100.
• If the productivity score is 200 or higher, the bonus is RM200.
(a) Design a pseudocode algorithm for solving the problem as stated above. (13 marks)
(b) Write a complete Java program based on the algorithm you design in Question 2(a).
(15 marks)
[28 marks]

3. (a) Create a complete Java program that prompts the user to enter the weight of a parcel (in
gram) and then calculates the shipping fee (in RM). Write a function named computeFee()
with one parameter for the weight of parcel which calculates and returns the shipping fee.
The charges for every 500 grams is RM 4.50. Note that the shipping fee is charged on every
500 grams basis, for example, 700 grams will be charged as 1 kilogram which the fee is RM
9.00. The full program should have a main() function that accepts input from the user for
the weight of the parcel and display the shipping fee by invoking the computeFee() function.
You should print the fee in 2 decimal places. (13 marks)
(b) Write a complete Java program which will prompt the user to key in twelve numbers in an
array, then display each number and the largest number entered. (12 marks)

[25 marks]

Page 1 of 2
CPR3013 Programming Fundamentals
Final Examination, September 2018 Semester: Set A

4. (a) Complete the program for Match class.


i. Define a class called Match in Java code which contains the protected attributes shown
in Table Q4(a). (4 marks)
Table Q4(a)
Attribute Data Type
matchID Integer
venue string
date string

ii. Complete the constructor that accepts three arguments to initialize all the attributes
shown in Table Q4(a).
(4 marks)
iii. Overload the constructor with no argument by using this reference to initialize the
matchID as 1001, venue as Stadium A, and date as 01-01-2001. (3 marks)
iv. Complete the setVenue() method. (3 marks)
v. Complete the getVenue() method. (3 marks)
vi. Complete the toString() method to return a string with the details of the attributes.
(3 marks)
(b) Write a driver class called MatchDriver with a main method to instantiate an object for
Match class. The details are as shown in Table Q4(b).
Table Q4(b)

Object name : fbMatch


Match ID : 2098
Venue : St . James ’ Park
Date : 21 -12 -2018

Your driver class should display the details of the object. (5 marks)
[25 marks]

THE END

Prepared by Tan Phit Huan


Department of Computing
School of Engineering, Computing and Built Environment

Page 2 of 2
Array

Upon completion of the course, the student is able to:

CLO2 Write small programme using selection and iteration to solve basic computing problem
CLO3 Write small programme using function and arrays to solve basic computing problems

Declaring and Initializing an Array


• Array
• Named list of data items
• All have same type

• Declare array variable


• Same way as declaring any simple variable
• Insert pair of square brackets after type
double[] salesFigure = new double[20];
• Array’s elements numbered beginning with zero
• Can legally use any subscript from 0 through 19

• Work with any individual array element


• Treat no differently than single variable of same type
• Example: salesFigure[0] = 2100.00;

• Assign nondefault values to array elements upon creation


int[] tenMult = {10, 20, 30, 40, 50, 60};

• Convenient to declare symbolic constant equal to size of array


final int NUMBER_OF_SCORES = 5;
int[]scoreArray = new int[NUMBER_OF_SCORES];

• length field is size of array


• Contains number of elements in array
for(sub = 0; sub < scoreArray.length; ++sub)
scoreArray[sub] += 3;

• Enhanced for loop – foreach loop


• Cycle through array
• Without specifying starting and ending points for loop control variable
for(int val : scoreArray)
System.out.println(val);

Declaring an Array of Objects


• Create array of Employee objects
final int NUM_EMPLOYEES = 7;
Employee[] emp = new Employee[NUM_EMPLOYEES];
• Must call seven individual constructors
final double PAYRATE = 6.35;
for(int x = 0; x < NUM_EMPLOYEES; ++x)
emp[x] = new Employee(101 + x, PAYRATE);

Material taken from: Farrell, J., 2011, Java Programming, 6th ed,. Boston: Course Technology
Array

Parallel array
• One with same number of elements as another
• Values in corresponding elements related

Passing Arrays to Methods


• Reference types
• Object holds memory address where values stored
• Receiving method gets copy of array’s actual memory address
• Receiving method has ability to alter original values in array elements

Returning an Array from a Method


• Method can return an array reference
• Include square brackets with the return type in the method header

Two-Dimensional and Multidimensional Arrays


• Use two subscripts for rows and columns
• Also called as matrix or table
int[][] someNumbers = new int[3][4];

int[][] rents = { {400, 450, 510},


{500, 560, 630},
{625, 676, 740},
{1000, 1250, 1600} };

• length field holds the number of rows in the array rents.length


• Each row has a length field that holds the number of columns in the row rents[1].length

Arrays class
• Contains many useful static methods for manipulating arrays

Material taken from: Farrell, J., 2011, Java Programming, 6th ed,. Boston: Course Technology
Topic 12: Exception Handling

Upon completion of the course, the student is able to:


1. Write Java application using proper object-oriented style.
2. Write a threading and an IO program

Exceptions
• Unexpected or error conditions
• Not usual occurrences
• Causes
• Call to file that does not exist
• Try to write to full disk
• User enters invalid data
• Program attempts to divide value by 0

Exception Handling
• Handling of exceptions
• Object-oriented techniques used to manage Exception errors
• Provides a more elegant solution for handling error conditions

Exception Hierarchy

Unrecoverable Checked Unchecked

• Checked exceptions
• Subclass of Exception
• Use for anticipated failures
• Where recovery may be possible
• Some exception types are checked exceptions,which means that a method must do something about them.
• The compiler checks each method to be sure that it does.
• Unchecked exceptions
• Subclass of RuntimeException
• Use for unanticipated failures
• Where recovery is unlikely
• Use of these is ‘unchecked’ by the compiler.
• Cause program termination if not caught.
• This is the normal practice.
• InputMismatchException is a typical example.

Material taken from:


1. Farrell, J., 2011, Java Programming, 6th ed,. Boston: Course Technology
2. Bradley, I.M.. 2013. Software Testing, CG048 Programming 2, Nurthumbria University, U.K.
Topic 12: Exception Handling

try block
• Segment of code in which something might go wrong
• Attempts to execute
• Acknowledging exception might occur
• try block includes:
• Keyword try
• Opening and closing curly brace
• Executable statements
• Which might cause exception

catch block
• Segment of code
• Immediately follows try block
• Handles exception thrown by try block
preceding it
• Can “catch”
• Object of type Exception
• Or Exception child class
• catch block includes:
• Keyword catch
• Opening and closing parentheses
• Exception type
• Name for Exception object
• Opening and closing curly braces
• Statements to handle error condition
• Catch multiple Exceptions
• Examined in sequence
• Until match found for Exception type
• Matching catch block executes
• Each remaining catch block bypassed
• “Catch-all” block
• Accepts more generic Exception argument type: catch(Exception e)
• Unreachable code
• Program statements that can never execute under any circumstances

finally block
• Use for actions you must perform at end of try...catch sequence
• Use finally block to perform cleanup tasks
• Executes regardless of whether preceding try block identifies an Exception
• When finally block used
• finally statements execute before method abandoned
• finally block executes no matter what outcome of try block occurs
• try ends normally
• catch executes
• Exception causes method to abandon prematurely

Exercise
Write a complete Java program that prompts the user to key in two integer values (x & y) and display the result of
x divided by y. Your program should prompt the user to read the number again if the input is incorrect. Hint: You
should consider checking ArithmeticException and InputMismatchException.

Material taken from:


1. Farrell, J., 2011, Java Programming, 6th ed,. Boston: Course Technology
2. Bradley, I.M.. 2013. Software Testing, CG048 Programming 2, Nurthumbria University, U.K.
CPR3013 Programming Fundamentals Topic 03: Selection
Upon completion of the topic, the student is able to:

1. Write small programmes using selection and iteration to solve basic computing problems.

• Boolean
Use a variable with Boolean data type to keep the value of true or false.
Example: boolean T1 = true, T2 = false;

• Relational Operator • Confusion Between == and =


> >= < <= == != • The appearance of = in place of ==
Assume that: resembles a silent killer
int x = 7, y = 10; ▪ It is not a syntax error
What is the output of the following expressions? 1 – true, 0 -false ▪ It is a logical error
1. x > y 3. x >= 8
2. x != y 4. y == 11

• Logical (Boolean) Operators


• Not gate (!) - unary
X !X
1
0

• AND gate (&&) - binary ∙ OR gate(||) - binary


X Y X && Y X Y X || Y
0 0 0 0
0 1 0 1
1 0 1 0
1 1 1 1

Example:
boolean T1 = true, T2 = false;
int x = 18, y = 6;
What is the output of the following expressions:
i) T1 || T2
ii) T1 && !T2
iii) !T1 || T2 && (x > y)
CPR3013 Programming Fundamentals Topic 03: Selection
• Selection: if and if...else
What is the output for the following statements?
int x = 34;
char grade= 'F';
if(x >= 80)
grade = 'A';

What is the output for the following statements?


int x = 5, y = 10;
if(x > y)
System.out.println("X is bigger");
else
System.out.println("Y is bigger");

• Multiple Selections: Nested if


What is the output for the following statements?
Scanner input = new Scanner(System.in);
int score;
score = input.nextInt(); //user key in 65
if(score >= 80)
System.out.println("Grade A");
else if(score >= 70)
System.out.println("Grade B");
else if(score >= 60)
System.out.println("Grade C");
else if(score >= 50)
System.out.println("Grade D");
else
System.out.println("Grade F");

Exercise 1 :
Write a program that will prompt the user to key in a value in the range of 55 to 80 inclusively. Print
a message to tell the user that he/she entered number correctly or not.
CPR3013 Programming Fundamentals Topic 03: Selection
• Conditional Operator (?:)
• Conditional operator (?:) takes three arguments
– Ternary operator
• Syntax for using the conditional operator is:
expression1 ? expression2 : expression3
• Example:
int x = 2, y = 9, bigger;

bigger = x>y ? x : y;
condition ? true case : false case

is same as:
if(x>y)
bigger = x;
else
bigger = y;

• switch Structures
Scanner input = new Scanner(System.in);
int option;
System.out.print("Key in your option: ");
option= input.nextInt();
switch(option){
case 1 : System.out.println("You key in 1");
case 2 : System.out.println("You key in 2");
break;
case 3 : System.out.println("You key in 3");
case 4 : System.out.println("You key in 4");
break;
default: System.out.println("Invalid\n");
}

If user key in value 2, what is the output??

If user key in value 3, what is the output??

If user key in value 5, what is the output??

Exercise 2 :
Write a program to prompt user to key in an integer value. Check if the value is positive or negative.

Exercise 3 :
Write a program to prompt the user key in an integer value, check whether the number is even or
odd.
CPR3013 Programming Fundamentals Topic 04: Iteration
Upon completion of the topic, the student is able to:

1. Write small programmes using selection and iteration to solve basic computing problems.

initial statement //complete the program


while(expression){ //to print 1 to 10
statement
update statement
}

initial statement

Logical
false
expression

true

statement
update statement

for(initial statement; loop condition; //complete the program


update statement) //to print 1 to 10
statement

Initialize
update
Logical expression
false
true

statement
CPR3013 Programming Fundamentals Topic 04: Iteration

initial statement //complete the program


do{ //to print 1 to 10
statement
update statement
}while(loop condition);

initial statement

statement
update statement

true
Logical
false
expression

What is the output of the following code segment?

a) for(int i=0; i<12; i=i+2 )


System.out.println(i);

b) int i=3;
while(i<100) {
System.out.println(i);
i *= 3; // i = i*3;
}

c) int x = 50, y = 10;


do{
x += y; // x = x + y;
System.out.println(x);
}while(x<=80);

d) int i=0; • break statement is used for two purposes


while(i<10){ – To exit early from a loop
System.out.println(i+ " "); • Can eliminate the use of
if(i==5) certain (flag) variables
break;
– To skip the remainder of the switch
i++;
structure
}
CPR3013 Programming
Fundamentals
Algorithm Design
An introduction to algorithms
and pseudocode
• What is an algorithm?
– Lists the steps involved in accomplishing a
task (like a recipe)
– Defined in programming terms as ‘a set of
detailed and ordered instructions
developed to describe the processes
necessary to produce the desired output
from a given input
An introduction to algorithms
and pseudocode
• What is an algorithm?
– An algorithm must:
• Be lucid, precise and unambiguous
• Give the correct solution in all cases
• Eventually end
An introduction to algorithms
and pseudocode
• What is pseudocode?
– Structured English (formalised and
abbreviated to look like high-level computer
language)
An introduction to algorithms
and pseudocode
How to write pseudocode
• There are six basic computer
operations:
1. A computer can receive information
2. A computer can put out information
3. A computer can perform arithmetic
4. A computer can assign a value to a variable
or memory location
5. A computer can compare two variables and
select one of two alternate actions
6. A computer can repeat a group of actions
How to write pseudocode
1. A computer can receive information
– The verbs Read and Get are used in
pseudocode when a computer is
required to receive information.
– Read is used when the algorithm is to
receive input from a record on a file.
– Get is used when the algorithm is to
receive input from the keyboard.
How to write pseudocode
Read student_name
Get system date
Read number_1, number_2
Get tax_code
How to write pseudocode
2. A computer can put out information
– The verbs Print, Write, Put, Output or
Display are used in pseudocode when a
computer is required to supply information
or output to a device.
– Print is used when the output is to be sent
to a printer.
– Put, Output or Display are used when
the output is to be written to the screen.
– Prompt and Get are also used in pseudocode
to retrieve information.
How to write pseudocode
Print ‘Program Completed’
Write customer record to master file
Put out name, address and postcode
Output total_tax
Display ‘End of Data’
How to write pseudocode
3. A computer can perform arithmetic
– A mathematical calculation using either
mathematical symbols or the words for
those symbols. For example:
— Add number to total OR
— Total = Total + number
– The following symbols can be written in
pseudocode
— + Add
— - Subtract
— * Multiply
— / Divide
— () for Parentheses
How to write pseudocode
– Orders of operation
• Applies to pseudocode and to most
computer languages
• First operation carried out will be any
calculations contained with
parentheses
How to write pseudocode
Add number to total

Divide total_marks by student_count

Compute c = (f-32) * 5/9


How to write pseudocode
4. A computer can assign a value to a
variable or memory location
– Three cases of writing pseudocode to
assign a value to a variable:
1. The verbs Initialise or Set are used to give
data an initial value in pseudocode.
2. Symbols ‘-’ or ‘’ are used to assign a value
as a result of some processing.
3. The verbs Save or Store are used to keep a
variable for later use.
How to write pseudocode
Initialise total_price to zero
Set student_count to 0
total_price = cost_price + sales_tax
total_price <- cost_price + sales_tax
Store customer_num in last_customer_num
How to write pseudocode
5. A computer can compare two
variables and select one of two
alternate actions.
– To represent this operation in
pseudocode, special keywords are used:
IF, THEN and ELSE
– The comparison of data is established
in the IF clause
– The choice of alternatives is
determined by the THEN or ELSE
options
How to write pseudocode
IF student_status is part_time THEN
add 1 to part_time_count
ELSE
add 1 to full_time_count
ENDIF
How to write pseudocode
6. A computer can repeat a group of
actions
– When there is a sequence of processing
steps that need to be repeated, two special
keywords are used, DOWHILE and ENDDO
– The condition for the repetition of a group
of actions is established in the DOWHILE
clause
– The keyword ENDDO acts as a delimiter.
As soon as the condition for the repetition
is found false, control passes to the next
statement after the ENDDO
How to write pseudocode
DOWHILE student_count < 50
Read student_record
Print student_name, address to report
Add 1 to student_total
ENDDO
Meaningful names
• When designing an algorithm, a
programmer must introduce some unique
names which represents variables or
objects in the problem.
• Names should be meaningful.
• Names should be transparent to
adequately describe variables (Number1,
number2, etc.).
Meaningful names
• Underscore is used when using more
than one word (sales_tax or
word_count).
• Most programming language does not
tolerate a space in a variable as space
would signal the end of a variable name.
• Another method is to use capital letters
as a word separator (salesTax or
wordCount).
CPR3013 Programming
Fundamentals
Week 01
Introduction to Java
Programming First Lecture
• Learning to program
• Strategies & suggestions for study
• Classes and Objects (Later on) – know the words for
now
• Object orientation
• Terminology & a simplified introduction
• Programming in Java
• What are programs
• The compilation process
• The three main constructs
• Sequences of operations
• How to repeat operations
• How to make decisions
• Java Syntax (first around - more later)
Learning to Program
• Java is hard – people pay for people who can do hard
things
• If something is easy – people can do it for
themselves, instead of paying you
• You should want to expand your knowledge of the
subject
• Your understanding is who you are
• Difficult concepts are only the ones you haven’t
tackled yet!!!
• Practice makes almost perfect
• You must practice until it is natural
• You must learn as these are your tools
• You must complete the labs so as to expand your skills
– These are your tools – be the best using
Learning to Program
Other subjects
Knowledge

Topic 1 Topic 2 Topic 3 Topic 4 Topic 5

Expected prior learning


Weeks

Learning to program

Topic 5
Knowledge

Topic 4
Topic 3
Topic 2
Topic 1
Reading
• Get used to reading, even if what you read
does not make much sense at the time??
What for??
• Be prepared for a massive amount of new
terminology
• Don’t be scared – you will sound like a
spaceman soon enough!!
• Get to the library as soon as possible
• Get at least one Java book out.
• The learning curve is hard
• Learning is good .. Love it!
Getting set-up at home
• We are using Java Development Kit JDK1.8
• We Offer ZERO support for home computers and laptops
• CPR3013
– Set-up and create the same set-up we have
– Site links for free software
– The on-line Java tutorial from sun
– Unit slides and labs – collect missed notes online
– Software from http://www.jcreator.com Or Netbeans from
http://netbeans.org

– JDK1.8 from http://www.oracle.com also get the Java documentation


• When contacting me, use the following example e-mail address structure
[email protected]
Sample Java Program
public class Hello {
public static void main ( String [ ] args )
{
System.out.println( "Hello World!“ );
}
}
This is called a source program
You create it using JCreator (see previous talk)
It is saved in a file called Hello.java
Bytecodes
• To get the sample program running, it is
first translated into bytecodes


Question
Here is the first line of a Java program:
public class AddUpNumbers
What should the source file be named?
What will the compiler name the bytecode
file?

AddUpNumbers.java
AddUpNumbers.class
Java Virtual Machine
Running the Program
• You are using JCreator so you need to
select the appropriate icon to make the
program run
• In a Command Window you would issue
the command:
java Hello
Question
• What role in Java programming does each of
the following files play?
Source code file.
Bytecode file.

Answer
• Source code file.
• A text file in the Java language created by a programmer
with a text editor.
• Bytecode file.
• A file of machine language for the Java virtual machine
created by a Java compiler.
Example Source Program
public class Hello
{
public static void main ( String[ ] args )
{
System.out.println("Hello World!");
}
}
• The file must be named Hello.java
– The case of the letters is important
• Class is a Java reserved word
– A class is a section of program
– Everything that makes up a class is placed
between the first brace ( { ) and the
matching last brace ( } ).
• The name of the class is up to you but
– Should start with an upper case letter
– May consist of letters or digits
– May NOT have spaces
Between the Braces
• All of our small Java programs look
something like this:
NOTE:
public class YourName Braces always
{ come in pairs
….. { }
}

Another NOTE:
We want you to always write the first line as
public class …
The word public is optional in some cases but in others leaving it
out can cause errors
public static void main ( String[] args )

• Shows where the program starts


running.
• The word main means that this is the
main method --- where the Java virtual
machine starts running the program
• The full meaning will be explained later
– for now just use this line
Question
Would the following be an acceptable
start for a main method:

public static void main(String[] args)

The Java compiler would accept the line.


But it looks sloppy to human eyes.
System.out.println("Hello World!");

• This statement writes the characters


inside the quotation marks to the
monitor of the computer system
• Note the syntax - must be followed
exactly
System.out.println(stuff to be output ) ;

Capital S
. ( ) ;
Syntax Errors
• A syntax error is a "grammatical error" in using
the programming language.
• The compiler tried to translate the source code into
bytecode but failed as there is something it does not
understand or expect. It will stop it processing and
give you a message.
• The compiler generated an error message showing
where the compiler got confused. It will also tell you
why it got confused
• The compiler did not create a new bytecode file
because it stopped translating when it got to the
error
Edit, Compile, Run Cycle
1. Edit the program in JCreator.
2. Save the program to the hard disk
3. Compile the program
4. If there are syntax errors, go back to step
1.
5. Run the program
6. If it does not run correctly, go back to step
1.
7. When it runs correctly, quit.
Comments 1
• A comment is a note written to a human
reader of a program
• Three types of comment:
– // single line comment
– /* multi line comment
can be spread over several
lines
*/
Comments 2
• The third type of comment is special and is
used at the top of your program.
• Later you will find out how it helps when
generating documentation
• /**
* brief description of program
* @author YOUR NAME
* @version DATE OR VERSION NUMBER
*/
/**
* Hello world program to demonstrate comments
*
* @author Lai Kim Min
* @version 02-01-2016
*/

public class Hello


{
public static void main ( String[] args )
{
// outputs the message
System.out.println("Hello World!");
}
}
CPR3013 Programming
Fundamentals
Week 02
Primitive Data
Topics
• Data Types
• Primitive Data vs. Objects
• The Eight Primitive Data Types of Java
• Numeric Data Types
• Character and Boolean Data Types
Question
• Say that you came across the following
torn slip of paper. What can it mean?

Not easy to say, without knowing more.


Variables
• Variables are used to store data in a
program.

• They represent data of a certain type.


Variable Declarations
• Syntax
datatype variableName;

• Examples
int x; // Declare x to be an integer variable;
double radius; // Declare radius to be a
char a; // Declare a to be a character variable;
Data Types
• Computer memory stores arbitrary bit
patterns.
• As with a string of letters, the meaning
of a string of bits depends on how it is
used.
• The particular scheme that is being
used for a particular string of bits is a
data type.
Data Types continued
• A data type
– Is a scheme for using bits to represent
values.
– Values are not just numbers, but any kind
of data that a computer can process.
– All values in a computer are represented
using one data type or another.
Question
0000000001100111
is a pattern of 16 bits that might be
found somewhere in computer memory.
What does it represent?

Without knowing more about how the above


pattern is being used,
it is impossible to say what it represents.
Primitive Data Types
• There are types of data that are so
fundamental that ways to represent
them are built into Java.
• These are the primitive data types.
• The eight primitive data types are:
– byte short int long
– float double
– char
– boolean
Style Note
• Upper and lower case characters are
important.
• So "byte" is the name of a primitive
data type, but "BYTE" is not.
• Computer languages where case is
important are called case sensitive.
• Java is case sensitive
Objects
• Java has very many data types built into
it
• You (as a programmer) can create as
many more as you want.
• However, all data in Java falls into one
of two categories:
– primitive data and objects.
• Any data type you invent will be a type
of object
All you need to know, for now:
• There are only eight primitive data types.
• A programmer can not create new primitive
data types.

• An object is a big block of data.


• The data type of an object is called its class.
• Many classes are already defined in the Java
Development Kit.
• A programmer can create new classes to meet
the particular needs of a program.
Integer Primitive Data Types
Type Size (bits) Range

byte 8 -128 to +127

short 16 -32,768 to +32,767

int 32 (about) -2 billion to +2


billion
long 64 (about) -10E18 to +10E18
Floating Point Primitive Data
Types
Type Size (bits) Range

float 16 -3.4E+38 to +3.4E+38

double 32 -1.7E+308 to 1.7E+308


Question
• Say that you want to deal with the
number 1,023,004 in your computer
program.
• Would data type short be an
appropriate choice?

No.
Data of type short can be only in
the range -32,768 to +32,767.
• When you write a program you do not have to
know how to represent a number in bits.
• You can type the number just as you would on
a typewriter.
• This is called a literal
• For example, 125 literally represents the
value one hundred twenty five.
• Example Integer literals
– 125 -32 16 0 -123987
• A 64 bit long literal has a upper case 'L' or
lower case 'l' at the end.
– 125L -32L 16L 0l -123987l
Question
• Is the following an integer literal?
197.0

No
It has a decimal point
Program 1
The following program uses primitive data type short:
class ShortEg
{
public static void main ( String[] args )
{ value in this program is a
short value = 32; variable
System.out.println("A short: " + a name for a section of memory
that holds data using a
value); particular data type.
} In this case value will be the
} name for 16 bits of main
memory that uses short to
represent an integer.
This program puts 32 into value.
Then it writes out:

A short: 32
Floating Point Literals
• floating point literals have a decimal point in
them, and no commas (no thousand's
separators):
123.0
-123.5
-198234.234
0.00000381

• Note: Literals written like the above will
automatically be of type double
Question
• Do you think that using float instead of
double saves a significant amount of
computer memory?

No.
For most programs using variables of type double
will cost only a few extra bytes in a program
thousands of bytes long.
Note
• Either of the following also works:
double rats = 8912 ;
• or
double rats = 8912.0 ;
• but the first is sloppy so do not do it!
Scientific Notation
• You will sometimes see scientific
notation.
• The following are all double-precision
literals:
1.23E+02
-1.235E+02
-1.98234234E+05
3.81E-06
• The big "E" means "times 10 to the
power of" .
Question
• What is the following number if written
out the usual way: 1.9345E+03

1934.5
The char Primitive Data Type
• Characters are very common in computers.
• The primitive data type for characters is
named char.
• The char type represents a character using
16 bits.
• Java uses 16 bits so that a very large number
of characters can be represented, nearly all
of the characters in all of the World's
languages.
• The method used is called Unicode.
• Here is a 16 bit pattern:
000000000110011
• If you know that these 16 bits are of
data type char, then you could look in a
table and discover that they represent
the character 'g'.
• the same 16 bits represent the integer
103 if they are regarded as data type
short.
• Knowing the data type of a pattern is
necessary to make sense of it.
Observations on char
• Upper and lower case characters are
represented by different patterns.
• Punctuation and special characters are also
char data.
• There are also special characters, like the
space character that separates words.
• Control characters are bit patterns that
show the end of a line or where to start
pages.
• Primitive type char represents a SINGLE
character.
Character Literals
• In a program, a character literal is surrounded with
an apostrophe on both sides:
'm' 'y' 'A'
• In a program, control characters are represented
with several characters inside the apostrophes:
'\n‘ '\t'
• Each of these is what you do in a program to get a
single char.
– the first one represents the 16 bit newline character
– the second one represents the tabulation character.
• What is wrong with the following char
literal: "W"

The character is not surrounded by apostrophes.


It should be: 'W'
.
With double quotes, "W", you get a String that
contains a single character.
This is not the same as a primitive single
character. A String is represented as an object.
Primitive Data Type boolean
• Another of the primitive data types is
the type boolean.
• It is used to represent a single
true/false value.
• A boolean value can have only one of two
values:
true false
• In a Java program, the words true and
false always mean these boolean values
Summary
• You need to use primitive data types
• The ones you will use most are:
– int
– double
– char
– boolean
CPR3013 Programming
Fundamentals
Variables, Assignment,
Expressions
Variables
• In order to put data in memory, and
later get it back again, a program must
have a name for each section of memory
that it uses:
– variable
• a name for a location in main memory which uses
a particular data type to hold a value.
Question
Must a variable always have a data type?

Yes. Otherwise it would not be clear what


its bits represent.
Declaration of a Variable
• The line
int payAmount = 123;

is a declaration of a variable.
• A declaration of a variable is where a program
says that it needs a variable.
• For our small programs, declaration
statements will be placed between the two
braces of the main method.
• The declaration gives a name and a data type
for the variable.
• It may also ask that a particular value be
placed in the variable
public class Example
{
public static void main ( String[] args )
{
// declaration of a variable and initialises
// the value.
int payAmount = 123;
System.out.println("The variable contains: “
+ payAmount );
} The line The + joins
the two
} int payAmount = 123; items in
is a declaration of a variable. the output
The effect of declaring a
variable in Java
Computer Memory Java Instruction

score
int score ;
Syntax of Variable Declaration
• dataType variableName;
– declares a variable, declares its data type, and
reserves memory for it. It says nothing about what
value is put in memory.
• dataType variableName = initialValue ;
– The second way declares a variable, declares its
data type, reserves memory for it, and puts an
initial value into that memory. The initial value
must be of the correct dataType.
• dataType variableNameOne, variableNameTwo ;
– The third way declares two variables, both of the
same data type, reserves memory for each, but
puts nothing in any variable. You can do this with
more than two variables, if you want
Names for Variables
• Use only the characters 'a' through 'z', 'A' through
'Z', '0' through '9', character '_', and character '$'.
• A name can not contain the space character.
• Do not start with a digit.
• A name can be any length.
• Upper and lower case count as different characters.
– So SUM and Sum are different names.
• A name must not already be in use in this part of the
program
• A name can not be a reserved word.

word which has a predefined meaning in Java. For example


int, double, true
Quiz
Which of the following variable declarations are
correct?

long good-by ;
short shrift = 0;
double bubble = 0, toil= 9, trouble = 8
byte the bullet ;
int double;
char thisMustBeTooLong ;
int 8ball;
Example Program
public class Example
{
public static void main ( String[] args )
{
int hoursWorked = 40;
double payRate = 10.0, taxRate = 0.10;
System.out.println("Hours Worked: " + hoursWorked );
System.out.println("pay Amount : " +
(hoursWorked * payRate) );
System.out.println("tax Amount : " +
(hoursWorked * payRate * taxRate) );
}
} Order is important we need to
declare a variable before we
use it.
Java Naming Convention
1. the name of a class starts with a
Capital case letter
2. the name of a variable starts with a
lower case letter
3. if a name consists of several words the
first word starts with a lower case and
each of the rest an upper case, e.g
myMarkForTheModule
Assignment Statements
• So far, we have been using the value
initially put into a variable, but not
changing the value that a variable holds.
• Of course, variables are expected to
vary by having new values placed into
them as the program runs.
• An assignment statement changes the
value that is held in a variable
public class Example3
{
public static void main ( String[] args )
{
int payAmount ; //a declaration
payAmount = 123; //an assignment statement
System.out.println("The variable contains: "
+ payAmount );
}
}
Assignment Statement Syntax
• variableName = expression ;
– The equal sign "=" means "assignment."
– variableName is the name of a variable that
has been declared somewhere in the
program.
– expression is a collection of characters that
calls for a value.
Assignment Statement Syntax
• An assignment statement asks for the
computer to perform two steps, in
order:
– Evaluate the expression (that is: calculate a
value.)
– Store the value in the variable.
– For example, the assignment statement:
• sum = 32 + 8 ; asks for two actions:
– Evaluate the Expression — 32 + 8 is calculated,
yielding 40.
– Store the value in the variable. — 40 is placed in sum
Example Assignment Statements

• weeklyPay = 200.59 ;
• totalPay = 52 * weeklyPay;
• extraPay = totalPay / 12 + weeklyPay * bonus;
• extraPay = (totalPay / 12 + weeklyPay )*
bonus;

• initial = ‘X’; // character assignment

• foundBook = false; // boolean assignment


Arithmetic
Operator Meaning
Operators
- Unary minus
An arithmetic
operator is + Unary plus
a symbol that asks for
doing some arithmetic * multiplicatio
n
/ division

% Remainder

+ Addition

- minus
Quiz: Which ones are correct?
• 25
• 25 - value
• 2( a - b )
• (a-b) * (c-d)
• A - b/c + D
• -sum + partial
• ( (x+y) / z ) / ( a - b )
• ( (m - n) + (w-x-z) / (p % q )
Arithmetic Operators

• All of these operators can be used on floating point


numbers and on integer numbers.
– However, the % operator is rarely used on floating point.
• / means
– "integer division" if both operands are integers,
– "floating point division" if one or both operands are floating
point.

• An integer operation is always done with 32 bits or


more.
– If one or both operand is 64 bits (data type long) then the
operation is done with 64 bits.
• Otherwise the operation is done with 32 bits, even if
both operands are smaller.
Arithmetic Operators
• For example, with 16 bit short variables, the
arithmetic is done using 32 bits:
short x = 12; // 16 bit short
int result; // 32 bit
int result = x / 3; // arithmetic done using 32 bits

• The expression x / 3 divides a 32 bit 12 by


a 32 bit 3 and put the 32 bit answer in result.
• The literal 3 automatically represents a 32
bit value.
Weird Integer Arithmetic
• The division operator "/" means integer
division if there is an integer on both
sides of it.
• The result of integer division is always
an integer;
• If the exact result calls for a decimal
fraction, that part of the result is
dropped (not rounded.)
Arithmetic operations and data
types

System.out.println(“integer: " + (1/2 + 1/2) );


integer:

System.out.println(“floating: " + (1/2.0 + 1/2.0) );


floating:

System.out.println(“mixed: " + (1/2 + 1.0/2) );


mixed:
What type (integer or floating point) of
operator is the / in the following:
(12 + 0.0) / 7

• Floating point. Adding floating point 0.0


to the integer 12 results in a floating
point 12.0. Now the division is floating
point because one of its operands is.
( 1/2 + 3.5 ) / 2.0 = ?
( 1/2 + 3.5 ) / 2.0
--- do first
Since both operands are integer, the
operation is integer division, resulting
in:
( 0 + 3.5 ) / 2.0

3.5/2.0 = 1.75
Casting
• Variables and expressions can be covered
from one data type into another data type by
using casting.
• We have implicit casting and explicit casting.
• Implicit casting is when we move from a
smaller data type to a larger one. For example
int x = 100;
long y = x;

• The java compiler accepts the implicit casting


as the possible values for long are grater than
the possible values for int.
Casting cont.
• Explicit casting is required when we covert
from a larger data type to a smaller data
type.
long x = 100;
int y = x;
• The compiler would report an error as their
may be a loss of precision, as the value in the
long variable may be bigger than what can be
represented by int.
int y = (int)x;
• The casting forces the compiler to accept the
type conversion
Casting expressions
• We can cast the individual variables or we can
cast the results of an expression.
• double x = ( 1/2 + 3.5 ) / 2.0
• The result in x would be 1.75
• double y = ((int)( 1/2 + 3.5 )) / 2.0
• The result in y would be 1.5
• double z = (int)(( 1/2 + 3.5 ) / 2.0)
• The result in y would be 1.0
Constants
public class CalculateTax {
public static void main ( String[] arg ) {
final double DURABLE = 0.045;
final double NONDURABLE = 0.038;
. . . . . . The reserved word final tells the
} compiler that the value will not
change
} tax = gross * DURABLE ;

DURABLE = 0.441;
How many 100’s 10’s 1’s
• We can use simple mathematics to help
solve everyday problems.
• How do we split the number
• 453 into 4, 5, 3 by using mathematics

• The solution is an algorithm. A set of


steps which solves the problem.
Solution
int digit; Integer division will
int number = 987; drop the decimal
digit = number/100; fraction
number = number%100;

System.out.println(digit);
// produces output of 9
System.out.println(number);
// produces output of 87
//CONTINUE CODE…..

You might also like