Professional Documents
Culture Documents
Beginners University
Greenwich
Computing At
School
DASCO
Chris
Coetzee
Levels of Java coding
• 1: Syntax, laws, variables, output
• 2: Input, calculations, String manipulation
• 3: Selection (IF-ELSE)
• 4: Iteration/Loops (FOR/WHILE)
• 5: Complex algorithms
• 6: Arrays
• 7: Linked Lists
• 8: File management
• 9: Methods
• 9: Objects and classes (missing slides)
• 10: Graphical user interface (GUI) elements
(missing slides)
Syntax, laws, variables, output
3 Laws of Java
Project: CheeseCake
Class: CheeseCake
Method: main()
Main method
Variables vs. Value
double
int boolean
char
String
Why not have just 1 type?
• Only type big enough to cope with
sentences is Strings
• Strings are BIG compared with
booleans/ints
• To save space, we only use the box
type that is “just big enough” to contain
the value we want.
• Less waste = faster programs!
Strings: “cat” “DA1 2HW”
double
int boolean
char
String
int: 23 0 -98 39290 -321
double
int boolean
char
String
double: 1.2 -5.93 3.3333
double
int boolean
char
String
boolean: true / false
double
int boolean
char
String
char: ‘a’ ‘3’ ‘@’ ‘A’ ‘ ’
double
int boolean
char
String
What data type is each of
the following?
-9 double
4.5 int boolean
chicken char
false
% String
£ 2.90
The cat is hungry now.
192.168.1.190
Declare vs. Instantiate
number = 3; Instantiate
23
Output 23
23
Combining values and variables
int num1 = 5;
int num2 = 10;
System.out.println(num1+num2);
System.out.println(num1+” + ”+num2);
15
Output 5 + 10
What went wrong?!
22
Output 8
Input, calculations, String
manipulation
5 types of variables
double
int boolean
char
String
Combining values and variables
int num1 = 5;
int num2 = 10;
System.out.println(num1+num2);
System.out.println(num1+” + ”+num2);
15
Output 5 + 10
Input
• From keyboard?
• From mouse?
• From microphone?
• From scanner?
(String) readLine(
import Scanner
variable )
Keyboard input
Important notes:
Input is best received as a String
We use:
String anything = kb.nextLine();
“Green cow”
anything
Converting String to int
To convert String to int, we use a
function called Integer.parseInt( );
Example:
String snumber = kb.nextLine();
int num = Integer.parseInt(snumber);
“123” 123
snumber num
Output
Converting String to double
To convert String to double, we use a
function called Double.parseDouble( );
Example:
String snumber = kb.nextLine();
double price = Double.parseDouble(snumber);
“2.95” 2.95
snumber price
Output
Calculations in Java
Operator Function Example Result
+ Add int i = 10 + 2; 12
- Subtract int j = i – 3; 9
/ Divide double k = j / 3; 3.00
* Multiply int product = i * j; 108
++ Add 1 i++; 13
-- Subtract 1 j--; 8
% Modulus int m = 12 % 5; 2
Good practice
Don’t do calculations and output in the same line:
Work out the answer first
THEN display the answer
What students struggle with
int x = 1;
int y = 3;
x = 3;
int total = x + y; Answer: 6
int h = 4;
h++; Answer: 5
int k = 7;
k = k + 2; Answer: 9
More about Strings
String device = “radio”;
r a d i o
0 1 2 3 4
To get a specific character from a String, we use the
.charAt( ) function
“radio” ‘d’
device letter
String methods
There are many functions we can use to manipulate
Strings. They are called the ‘String methods’
if(num == 3)
Logic operators in Java
Operator Function Example
== equals if(num==3)
(int, double, char, boolean)
.equals() equals
(String)
if(name.equals(“Chris”) )
• = and ==
• .equals(“xx”) for Strings
• Putting a ; at the end of if( xx)
▪ if(num > 3); 🗶
▪ if(num > 3) ✔
IF/ELSE (2 outcomes)
IF/ELSE (int example)
Note conditions
if (condition) if (condition)
{ {
something something
} }
else else if (condition)
{ {
something else something else
} }
else
{
Only IF gets a third option
condition }
ELSE does not
AND/OR
• AND in Java: &&
• OR in Java: ||
• Used between conditions
▪ if(num>3&&<12) 🗶
▪ if(num>3)&&(num<12)✔
IF/ELSE (int example with AND)
Switch/Case (IF alternative)
Iteration/Loops (FOR/WHILE)
if(condition)
if(num == 3)
Logic operators in Java
Operator Function Example
== equals if(num==3)
(int, double, char, boolean)
.equals() equals
(String)
if(name.equals(“Chris”) )
•Iteration
•Fixed number of times
•FOR loop
Can you
spot the
mistake?
s
p
?
e
c
Output t
r
u
m
Detour: random numbers
It can be very useful to make a random
number in program.
Java has a many ways to do this.
Most common way is Math.random()
1 +(int)(Math.random()*((10 - 1) + 1))
FOR with random ints (A)
17
Output
?
17
17
FOR with random ints (B)
19
Output
?
7
12
Example task (advanced)
Write a java program that will generate a
random letter of the alphabet 5 times.
Example output: g u l x e
?
A logic condition
(like in IF) that has to
be true for the loop to
A simple variable continue.
(usually an int) that Something Operator
allows the loop to Something (usually
‘step through’ involving the counter
Normally called “i” variable)
Known number of
FOR
repetitions
Loops
Unknown number of
WHILE
repetitions
int i = 0;
while (i < 3)
{
At end of for loop, System.out.println(“gum”);
increase i by 1 i++;
}
gum
Output gum
gum
Another example (while loop)
boolean done = false;
while (done == false)
Create boolean
{
called done.
Set to false System.out.println(“Are you done? Y/N ”)
String answer = kb.nextLine();
if (answer.equals(“Y”) )
Continue while {
done is false done = true;
}
System.out.println(“Goodbye!”);
If user enters Y, }
set done to true
Make list of
Read problem Draw flowchart Code in Java
sub-tasks
Display
Sum:
num1 and
num1+ num2
num 2
Num2:
random number
between 1 and 10 Ask user
for total
Num1:
random number
between 1 and 10 False if total
= sum
Start True
Display
End Well
done!
Possible solution
boolean done = false;
while (done == false)
{
int num1 = 1 +(int)(Math.random()*((10 - 1) + 1));
int num2 = 1 +(int)(Math.random()*((10 - 1) + 1));
int sum = num1 + num2;
System.out.println(“What is ”+num1+” + “+num2+” ?”);
String answer = kb.nextLine();
int total = Integer.parseInt(answer);
if (total == sum)
{
done = true;
}
}
System.out.println(“Well done!”);
New topics /
we had less
practice before
Arrays/Linked Lists
Arrays vs Variables
Initialising an array
What could go wrong?
num [ 0 ] always OK
num [ 9 ] OK (given the above declaration)
num [ 10 ] illegal (no such cell from this declaration)
num [ -1 ] always NO! (illegal)
num [ 3.5 ] always NO! (illegal)
Array length
• When dealing with arrays, it is advantageous to
know the number of elements contained within the
array, or the array's "length". This length can be
obtained by using the array name followed by
.length. If an array named numbers contains 10
values, the code numbers.length will be 10.
http://mathbits.com/MathBits/Java/arrays/Declare.htm
Parallel arrays
Parallel array applications
Parallel arrays in Java
for(int index = 0; index < dogname.length; index++)
{
System.out.println(dogname[index]);
System.out.println(round1[index]);
System.out.println(round2[index]);
}
Searching an array using a flag
Sorting an array (Bubble Sort)
2D arrays
Declaring a 2D array in Java
int[ ][ ] arrNumbers = new int[6][5];
Nothing!
You only put
Output data in, not
printed it!
Common mistake: printing a 2D array
Output
Correct way: printing a 2D array
Ou
tput
Common 2D array tasks
Linked Lists
Arrays vs Linked Lists
Array List
Fixed size Size can change
One or Two
Only linear
dimensions
Before you using a
Linked List…
import java.util.*;
Creating a Linked List
Output
Removing items from a
linked list
Output
Useful LinkedList methods
Method What does it do
Adds xx onto the end of the
.add(xx)
linked list
Removes the element at
.remove(y)
position y
Returns how many elements
.size()
there are in the linked list
Returns what element xx is
.indexOf(xx) stored in; returns -1 if element
was not found
Beware getting the size!
.size() 🡪 Linked Lists
e.g. int k = zones.size(); //zones is a linked list
.length() 🡪 Strings
e.g. int m = name.length(); //name is a String
.length 🡪 arrays
e.g. int g = boxes.length; //boxes is an array
LinkedList example
What did the
programmer
forget to do…?
File management
Files
There are two types of files in
computing:
– Text files (that contain
ASCII/Unicode characters) – e.g.
TXT, CSV
– Random Access Files (that contain
binary objects) – e.g. JPG, MP3
Setting up the file connection
Steps to remember:
1. Import: java.io.*
2. Throw away any IOExceptions (throws
IOException) that could potentially occur in the
main method
Connecting to the file
Steps to remember:
Suggested strategy:
1. Read in the line in to a String
2. Split the String into an array
3. Convert the values into ints
In Java that would be:
No buffer is used
this time.
You write directly
to the file.
In the end, always .close()
Example of adding numbers in a file
Methods
Methods
Methods are smaller chunks of code that
perform a specific function that you might
want to repeat in future
Method rules:
- Starts with a lower case letter
- Ends with a set of brackets: ( )
- Has to say what comes back
Types of methods
• Methods that return a value are called
return type methods.
• You have to specify what type of data
is being returned: int, String, char, etc.
• Methods that don’t return a value are
called void methods.
• Some people call void methods
procedures and return type methods
functions
Summary
•Void methods
•Don’t return a value
•Called procedures
•Return methods
•Returns a specified value
•Called functions
Methods are called from
within the ‘main method’
They are normally
written below the
main method
(but it really doesn’t
matter)
Void method examples
Return method examples
Void methods can be called
on their own line
Return methods should be called
into a receiving container
Common example
What does this
code segment
do?
How does it do it?
Method summary
Useful resource #1
http://mathbits.com/MathBits/Java/Methods/methods.htm
End of slides.