PROGRAMMING REFRESHER MODULE - www …alcc/PREF/lectures/PREF-2016-17Week01... · PROGRAMMING...
-
Upload
trinhhuong -
Category
Documents
-
view
218 -
download
4
Transcript of PROGRAMMING REFRESHER MODULE - www …alcc/PREF/lectures/PREF-2016-17Week01... · PROGRAMMING...
PROGRAMMING REFRESHER MODULE
Delivered by Ana Cavalcanti and Alvaro Miyazawa
Prepared by Dr Lilian Blot
The Rules
• Everything in PREF (Week 1) is optional.
– From week 2 of APRC and JAPC, we assume that all that has been taught in week one is mastered.
– The material will not be covered in any other lecture.
• From Week 2:
– The practical sessions are mandatory, you must attend.
– Lectures are always optional (but strongly recommended).
A n a . C a v a l c a n t i @ y o r k . a c . u k
A l v a r o . M i y a z a w a @ y o r k . a c . u kContact
BE AWARE
• Earlier editions will confuse you!
– 5th or earlier edition are bad!
• Collections have changed
• Integer, Double and others have changed.
– 3rd or earlier is very bad!!
• Swing has changed
Textbook
• Java How to Program: Early Objects Version (10th
Edition) by Paul and Harvey Deitel.
• The pages and sections of APRC and JAPC may match just the 9th Edition.
• 6th-8th Editions
Okay.
Why Java?
• One language for one degree programme
• Cross-platform
• Good open-source tools
• Simpler than many rivals (for instance, C++)
TODAY’S OBJECTIVES
• Java Basics part 1
• Writing our first Java program
• Types and Variables
• Control Structure
– A Selection statement: IF-ELSE IF-ELSE
In this section we will be writing our first Java program
– A classic “Hello World”
Section 1First Program
NOTE
All names have rules to follow:
• No punctuation (except underscore) and no spaces
• Do not start with a number.
• Java file name must be same as class name.
• Convention: Each word in class name starts in uppercase.
Class
public class HelloWorld {
. . .
}
• At least one class per java file
– Starts with keywords public class
– Followed by class name
• The name of the file must be the name of the class followed by the extension .java.
NOTE
The main method always has same signature, whereas other methods differ. We will look into that a little bit later this week.
Class
public class HelloWorld {
public static void main(String[ ] args) {
. . .
}
}
• Java classes are structured into methods.
• Each Java application must have one main method.
.
NOTE
Statements are always terminated by semicolon. However they may span over several line of codes when they are complex expressions.
Class
public class HelloWorld {
public static void main(String[ ] args) {
System.out.println("Hello World!");
}
}
• Statements consist of construct and expression:
– Construct is the command.
– Expression is the data to be enacted upon.
.
Section 2 – The Eclipse IDE
Eclipse Integrated Development Environment (IDE)
• Coloured text (“syntax highlighting”)
• Background compilation
• Syntax errors notified as you type
• Auto completion
• Task setting
• Project Package explorer
• Many other views
Objectives
• What is a variable?
• What is a type?
• How to declare a variable?
• What are the different types in Java?
– Primitives
– Objects
Section 3Declarations, Variables & Types
NOTE
• All declarations begin with a type (primitive or class).
• One or more variables can be declared at same time.
• Any variable can be initialised at declaration.
• Variable names:– No spaces– Only punctuation symbol is
the underscore e.gfirst_Name
– Must not be same as a reserved word.
• Conventions:– Should start with a lowercase
letter.– Each subsequent word begins
in uppercase.
Variable Declaration
• Formattype identifier [= initialValue];
– Note the square brackets denote optional initialisation
• Examplesint num;
int num, result;
int num=0, result;
NOTE
• Constant names follow the same rules as variables, but different conventions:– Name is entirely written in
uppercase,– With an underscore
separating different words in the name.
• These conventions make the code easier to read, and therefore should be followed.
Constant Declaration
• If the value stored in a memory location will not change during program run, store the value in a constant.
• Constants must be declared and initialised at same time.
• Formatfinal type identifier = initialValue;
• Examplefinal double INTEREST_RATE = 0.2;
Data Type Examples
• Some data types start with an upper case letter and some with a lower case letter.
– Types starting with a upper case letter are Objects.
– Types starting with lower case letter are Primitives.
• Java supports 8 primitive types.– Integer types (byte, short, int, long)
– Floating point types (float, double)– A character type (char)– A Boolean type (boolean)
Type of data Examples Data Type
A single character (letter) ‘a’ char
A word or words“apple”
or
“two aces”
String
Combination of characters and numbers
“CS 103” String
Nothing (Empty String) “ ” String
Integers63 or
0 or
-63
int
Real number (number with decimal point)
3.14 or
-3.14double
True or Falsetrue
or
false
boolean
Data Type Examples
• Java also supports the String type– Technically this is a class type (discussed
next week).– But is (mostly) used as if it were a
primitive type.
Note:
• char literal values use single quotes ‘ ’ and• String literal values use double quotes “ ”
Type of data Examples Data Type
A single character (letter) ‘a’ char
A word or words“apple”
or
“two aces”
String
Combination of characters and numbers
“CS 103” String
Nothing (Empty String) “ ” String
Integers63 or
0 or
-63
int
Real number (number with decimal point)
3.14 or
-3.14double
True or Falsetrue
or
false
boolean
BE AWARE
Any value can be converted to a String, but not all String values can be parsed to a primitive.
Type Conversion
• Type casts can be applied to convert a variable from one type to another type– Format: (dataType) variableName– Example: double result = 5.2;
int rounded = (int) result;• Rounded is assigned the int value 5.
• We can convert String values to primitive type values by means of parse methods– Example: int num = Integer.parseInt("9");
• Primitive values can be converted to string by toString() method in wrapper classes.– Example: String five = Integer.toString(5);– Or by concatenation: String five = "" + 5;
Objectives
• Build the program Hello <name>
• Program Specification
– Ask the user to enter their name, then print the words “Hello <name>!” to the console.
Section 4Input, Libraries & Packages
Simple view of the program
The Code
public class HelloName {
public static void main(String[] args) {
//create scanner object
Scanner sc = new Scanner(System.in);
//prompt user
System.out.print("Please enter your name:\t");
//get input and print string
System.out.println("Hello " + sc.next() +
"!");
}
}
Processing
Input
Output
Simple view of the program
The Modified Code
import java.util.Scanner;
public class HelloName {
public static void main(String[] args) {
//create scanner object
Scanner sc = new Scanner(System.in);
//prompt user
System.out.print("Please enter your name:\t");
//get input and print string
System.out.println("Hello " + sc.next() +
"!");
}
}
Processing
Input
Output
Tell the compiler where to find the code for a Scanner,
and add it to our program. java.util.Scanner is a Java
library.
Objectives
• What are the Java operators?
• What is an expression?
• How to declare a variable?
Section 5Operators & Expressions
NOTE
• As in Mathematics, when more than one operator appears in an expression, the order of evaluation depends on the rules of precedence.– the result of 3 + 4 * 2
is 11, not 14.
• Parentheses have the highest precedence:– the result of (3 + 4) * 2 is 14, not 11
– use of parentheses is encouraged in long and complex expressions.
Expressions
• An expression is a combination of values, variables, and operators
• Operators are special symbols that represent computations like addition and multiplication.
• The values the operator uses are called operands.
• Expressions can be combined to create a more complex expression.
• For example:<expression_1> operator <expression_2>
(age * 10) + (heightCM / 100)
(“Dr” + name) + (“>” * 3)
Mathematical Operators
• On the table on the right you can see mathematical operators and their precedence.
• The ( + ) operator is also the concatenation of two String operator
– “Dr” + “ “ + “Blot” is a valid expression. The result is the String “Dr Blot”.
• Note the special case for the Assignment Operator ( = ):
– The left-hand side of the assignment operator has to be a variable, not an expression.
Operator Name
P
r
e
c
e
d
e
n
c
e
+, -Unary plus and minus (for example, -10)
*, /, %Multiplication, division, integer division, and remainder
+, -Binary plus and minus (for instance, 3-10)
= Assignment operators
24
Assignment and Expressions
• Example
String firstname = “Lilian”;
String lastname = “Blot”;
String title = “Dr”
String name = firstname+ “ “ +lastname;
name = title + “ “ + name;
Code
25
Assignment and Expressions
• Example
String firstname = “Lilian”;
String lastname = “Blot”;
String title = “Dr”;
Code
“Lilian”firstname
lastname
title“Dr”
“Blot”
Name space Memory
26
Assignment and Expressions
• Example
String firstname = “Lilian”;
String lastname = “Blot”;
String title = “Dr”;
String name = firstname+ “ “ +lastname;
Code
“Lilian”firstname
lastname
title“Dr”
“Blot”
firstname
lastname
“Lilian” + “ “ + “Blot”
“Lilian Blot”name
Name space Memory
27
Assignment and Expressions
• Example
String firstname = “Lilian”;
String lastname = “Blot”;
String title = “Dr”;
String name = firstname+ “ “ +lastname;
name = title + “ “ + name;
Code
“Lilian”firstname
lastname
title“Dr”
“Blot”
“Lilian Blot”name
“Dr” + “ “ + “Lilian Blot”
title
name
‘Dr Lilian Blot’
Name space Memory
Main Scanner Class Methods
Method Description
nextInt()Reads the next input value as an
integer
nextDouble()Reads the next input value as a
double
nextBoolean()Reads the next input value as a
boolean
next() Reads the next input value as a String
hasNextInt()Returns true if next input value is an
integer
hasNextDouble()Returns true if next input value is a
double
hasNextBoolean()Returns true if next input value is a
boolean
hasNext()Returns true if there is another input
value to read
Today’s Problem
• We would like to write a program taking a measurement in meters (respectively, Feet, inches) as input and convert it to Feet, inches (respectively, meters).
– We need to find a way for the user to tell us which conversion he/she wants to do.
– Depending on the user SELECTION we need to do one operation or the other.
– We haven’t seen such a structure yet.
29
30
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things.
• A Control Structure for Branching:
– Selection statement if - else if - else.
Section 6Control Structure part I
31
Motivation
• Straight line programs: sequence of commands executed one after the other, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
32
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
33
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
34
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
35
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
36
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
37
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
38
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
39
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
40
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
41
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
42
Motivation
• Straight line programs: sequence of commands executed one after the other one, and only once.
– Cannot do many interesting things if any.
• Branching: A program can decide which statements to execute based on a condition.
– If condition is True, execute A1 to An
– If condition is False, execute B1 to Bk
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
43
Schema
Code
…
if (condition) {
Statement A1;
…
Statement An;
} else {
Statement B1;
…
Statement Bk;
}
…
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
44
Schema
Code
…
if (condition) {
Statement A1;
…
Statement An;
} else {
Statement B1;
…
Statement Bk;
}
…
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
45
Schema
Code
…
if (condition) {
Statement A1;
…
Statement An;
} else {
Statement B1;
…
Statement Bk;
}
…
Statement B1
…
Statement Bk
Statement A1
…
Statement An
True False
Condition
46
Schema
Simple if-statement
…
if (condition) {
Statement A1;
…
Statement An;
}
statement X;
statement Y;
…
Statement A1
…
Statement An
True
False
Condition
Statement X
Statement Y
…
47
Schema
if-else if-else statement
…
if (cond_1) {
Statement A;
} else if (cond_2) {
Statement B;
}
…
} else if (cond_n) {
Statement C;
} else {
Statement D;
}
…
Statement A
True False
cond_1
cond_2
cond_n
Statement B
Statement C Statement D
True
True
False
False
48
Schema
Nested if-else statements
…
if (cond_1) {
Statement A;
} else {
Statement B1;
Statement B2;
if (cond_2) {
Statement C;
} else {
Statement D;
}
}
…
Statement A
True False
cond_1
cond_2
Statement B1
Statement B2
Statement C Statement D
True False
49
Note
• The ternary operator makes the code more difficult to read. It should be used only when the conditions are simple, and the statements are very short.
• Use it sparingly.
Ternary Operator
• Format:
(condition) ? true-code : false-code
• ?
– Simplified (short hand) alternative to the if-elsestatement.
– Must be used as part of a statement.
– Useful for assigning one of two values depending on some condition.
• Example
grade = (mark >= 50) ? "pass" : "fail";
• A boolean expression returns true or false.
• The returned value is of the Java booleantype (a primitive type), a data type that can take only two values, true or false (case sensitive).
Boolean Expression
NOTE
When comparing to a variable, you must ensure the types are compatible. A compiler error will occur if you try to compare a intto a String.
Beware, confusing the Assignment operator = and the Equality operator == is a common mistake.
Comparing Numbers
• We can compare numbers using comparators such as: >, <, >=, <=, ==, !=.
• Values in variables can be compared too, and the result can be stored in a variable.
boolean a = 10 < 7; // a contains the value false
boolean b = 10 >= 7; // a contains the value true
code
int small = 6;
int big = 2000;
boolean is_greater = (big >= small); // true
code
52
Examples
• Assume: int num = 10;
Expression Result Explanation
(num == 10) true num is equal to 10
(num == “A”) error Different data-types
(num != ‘A’) error Different data-types
(num != 11) true num is not equal to 11
(num > 9) true Greater than test – num is larger value
(num >= 11) false Greater/Equal test – num is smaller
(num < 11) true Less than test – num is smaller
(num <= 10) true Less/Equal test – num is equal to 10
Truth Tables
Boolean Expression composition
• Boolean expressions can be combined to form complex expressions.
• composition can be done using three operators:
– && (and), || (or), ! (not)
• Refer to the truth tables on the right to see the result of composition of two boolean expressions.
&& True False
True True False
False False False
|| True False
True True True
False True False
!True False
False Truediscount = ((age < 26) || (isStudent == true));
resit = !((average >= 40) && (compensable < 40));
Code sample
Operator Precedence (cont.)
• In the table on the right you can see the rule of precedence for the booleanoperators.
• There are more operators available in Java. You are encouraged to read about them.
Operator Name
P
r
e
c
e
d
e
n
c
e
+, -Unary plus and minus (e.g. -10)
!not
*, /, %
Multiplication, division, integer division, and remainder
+, -Binary plus and minus (e.g. 3-10)
<, <=, >=Comparison
==, !=Equality, inequality
&&and
||or
=, +=, -=, *=, /=, %=
Assignment operators
Summary
• You should now be able to develop very simple programs, taking input from user and producing an output.
• You should be familiar with the concepts of Values, Variables and Data Types.
• You should understand Operators and the ‘rules of precedence’, and be able to create more complex expressions using them.
55
Exercises
• Give a truth table that shows the (boolean) value of each of the following Boolean expressions, for every possible combination of “input” values.
a) !(P && Q)
b) (!P) && Q
c) (!P) || (!Q)
d) (P && Q) || R
e) (P || R) && (Q || R)
Hint: including columns for intermediate expressions is helpful.
56
Exercises
• Here is some practice on writing complex Boolean expressions. Your task is to convert the English description into a Java Boolean expression. The variables to be used in the expressions are:
– dogSize with String values "small", "medium", and "large“.– dogHasSpots with Boolean values true or false.– dogAge with positive integer values.– dogColor with String values "white", "black", "red", and "brown“.– catSize with String values "small", "medium", and "large“.– catHasSpots with Boolean values true or false.– catColor with String values "white", "black", "orange", and "tabby“.– catEyeColor with String values "green", "brown", "blue“.– catAge with positive integer values.
• An old dog is one with an age greater than seven years while an old cat has an age greater than or equal to nine years. A cat and a dog are young if they are younger than three years old.
57
Exercises
• For the time being, and for simplicity we consider that we can compare two Strings using:
– !=, ==, <, >, >=, <=.
– these ARE NOT the correct Java operators for comparing Strings; we will see the proper comparator during the next lecture.
• Write a Boolean expression that captures
– Dogs that are large and have spots or cats that are white but do not have blue eyes.
– Young cats and dogs of small size and with brown eyes.
– Old cats and dogs, where cats are white and dogs are not black.
58