• No results found

Lesson3: JAVA Operators and Flow of Control

N/A
N/A
Protected

Academic year: 2022

Share "Lesson3: JAVA Operators and Flow of Control"

Copied!
38
0
0

Loading.... (view fulltext now)

Full text

(1)

Lesson3: JAVA

INTRODUCTION TO JAVA PROGRAMMING

Operators and Flow of Control

(2)

Relational Operator

•The Relational Operators determine the relationship that one operand has to the other.

e.g. Equality and Ordering

Operator Result

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

(3)

Boolean Logical Operator

• Boolean logical operators operate only on boolean operands.

Operator Result

& Logical AND

| Logical OR

^ Logical XOR(exclusive OR)

|| Short-Circuit OR

&& Short-Circuit AND

! Logical Unary NOT

== Equal to

!= Not Equal to

(4)

Boolean Logical Operator

• Logical Operation Effect

A B A|B A&B A^B !A

0 0 0 0 0 1

1 0 1 0 1 0

0 1 1 0 1 1

1 1 1 1 0 0

(5)

Boolean Logical Operator (Code)

class Logic{

public static void main (String Args[]){

boolean a = true;

boolean b = false;

boolean c = a | b;

boolean d = a & b;

boolean e = a ^ b;

boolean f = (!a & b) | (a & !b);

boolean g = !a;

System.out.println(" a=" + a);

System.out.println(" b=" + b);

System.out.println(" a|b=" + c);

System.out.println(" a&b=" + d);

System.out.println(" a^b=" + e);

System.out.println(" !a&b|a&!b=" + f);

System.out.println(" !a=" + g);

}

} // Code is From “The Complete Reference JAVA 2”, Herbert Schildt

(6)

Flow of Control

• Sequence

• Selection

• Iteration

(7)

Sequence

• Key points:

– order of operations may or may not be important

– order of evaluation within a single statement can be critical

• example:

a = b++;

a = b = read(input);

(8)

Order of precedence

• parentheses before operators

• then multiplication and division

• then addition and subtraction

• left to right for equal precedence ops

• RHS of an assignment before LHS

• if in doubt use brackets

• use brackets anyway (to clarify to other readers!)

(9)

Selection

if (condition) {

statement1;

} else {

statement2;

}

(10)

Selection

if (condition) {

statement1; condition must

} be of type boolean

else {

statement2;

}

(11)

Selection

if (condition) {

statement1;

} else {

statement2;

} else branch is optional

(12)

Selection

if (condition) {

statement1;

} else {

statement2;

} braces may be

omitted if they only contain a single

statement

(13)

Selection

if (condition) statement;

Brackets around the Condition are

essential

(14)

Selection

if (condition1) {

if (condition2) {

statement1;

} else {

statement2;

}

} else {

statement3;

}

• if statements can be nested

• indentation ignored by the compiler but helps (or can mislead!) human readers

(15)

Example conditions

if ((i < j) && (eof != true)) ….

if ((i < j) && !eof) ….

if ((i < j) && !eof()) ….

if ((n = input.read())== 0) …

Don’t use = when you mean ==

(16)

Example Program

class Larger {

public static void main(String[] args) { int x=20;

int y=20;

if(x >= y){

if (x==y){

System.out.println("x="+x+" and y="+y+ " are Equal");

} else {

System.out.println("Both are unequal");

}

System.out.println(x+" is the larger.");

} else {

System.out.println(y+" is the larger.");

}

} }

(17)

Example 2

class Largest {

public static void main(String[] args){

// Read three integers and print which is the larger.

SimpleInput keyboard = new SimpleInput();

System.out.println("Please type three integers.");

int x = keyboard.nextInt(), y = keyboard.nextInt(), z = keyboard.nextInt();

// A variable to hold the answer.

int largest;

if(x >= y){ // It must be either x or z.

if(x >= z){

largest = x;

} else{

largest = z;

} }

else{ // It must be either y or z.

if(y >= z){

largest = y;

} else{

largest = z;

} }

System.out.println("The largest is: "+largest);

}

} // Program Code is courtesy of David J. Barnes.

(18)

Practice Exercise

int month=10;

String season;

If (month==12 || month ==1 || month ==2) season =“Winter”;

else if(month==3 || month ==4 || month ==5) season=“Spring”;

else if(month==6 || month ==7 || month ==8) season=“Summer”;

else if(month==9 || month ==10 || month ==11) season=“Autumn”;

else

season= “Bogus Month”;

System.out.println(“October is in the ”+season +”.”);

(19)

Practice Exercise Continue

• Write a Java Programme which will tell whether X (a variable) is Even or Odd.

• Write a Java Programme which will specify whether a birth year was in 1950s, 1960s, 1970s, 1980s, 1990s.

(20)

Selection-switch

switch (Condition) {

Case 1:

Statement1;

Case 2:

Statement 2;

Break;

....

....

Default:

Statement n;

Break;

}

Condition should be int, short, byte or a char type

Switch Selection is

replacement of If-else for multiple selections and for multiple conditions.

(21)

Selection-switch

switch (Condition) {

Case 1:

Statement1;

Case 2:

Statement 2;

break;

....

....

default:

Statement n;

Break;

}

Break Used to break the condition

If none of the Case Statement satisfies Default condition will work

This Should be an Integer or Constant value

Remember this is COLON sign not

SemiColon or Delimeter

(22)

Example-switch Statement

class switchT{

public static void main(String[] Args) {

int x=1;

switch(x){

case 1:

System.out.println("Out put is 1: "+x);

case 2:

System.out.println("Out put is 2");

break;

case 3:

System.out.println("Out put is 3");

break;

default:

System.out.println("We were expecting X");

break;

} }

}

(23)

Practice Switch Statement

int month=10;

String season;

switch(month){

case 12:

case 1:

case 2:

season=“Winter”;

break;

}

System.out.println(“October is in the ”+ season+

“.”);

(24)

Iteration

• while simplest

• for most common

• do .. While uncommon

(25)

While Statement

while ( condition) {

body statements;

}

• while the condition evaluates to true,

repeatedly loop executing the body statements

• condition is tested before each pass through the body

• body statements should have some effect on the condition or you could loop indefinitely

(26)

While Statement

int a=10;

while (a > 0) {

System.out.println (a);

a = a-1;

}

System.out.println (“You Lost The Game");

(27)

Practice While Statement

int a=10;

while (a > 0) { System.out.println (a);

while(a>0 && a<5) {

System.out.println ("Inner Loop is working"+a);

a--;

}

a = a-1;

}

System.out.println ("You Lost The Game");

(28)

Practice While Statement

int n=10;

while (n != 1) {

System.out.println (n);

if (n%2 == 0) { // n is even n = n / 2;

}

else { // n is odd n = n*3 + 1;

} }

// Work Out Yourself to find the Output

(29)

do... while Statement

do {

body statements;

}

while ( condition);

• similar to while statement

• BUT condition is tested after each pass through the body

• so body statements will always be executed at least once

• body statements should have some effect on the

condition or you could loop indefinitely

(30)

do...while statement

int a=10;

do{

System.out.println (a);

a = a-1;

} while (a > 0);

System.out.println (“You Lost The Game");

(31)

for statement

for (initialisation; while condition; end of loop operation) {

body statements;

}

for Keyword Variable Initialisation Loop Condition

Loop termination Condition

(32)

for statement

• most convenient method for counter based iterations

• sequence of execution:

– initialisation

– is while condition true?

– if so, execute body statements – execute end of loop operation – is while condition true

etc

(33)

for statement

• Difference and common features of while and for loop for (INITIALIZER; CONDITION; INCREMENTOR) {

BODY

}

INITIALIZER;

while (CONDITION) { BODY

INCREMENTOR

}

(34)

for statement

for (int i=0; i<10; i++) { System.out.print(i + “ “);

}

output:

0 1 2 3 4 5 6 7 8 9

(35)

for statement

• break statement has importance in loop statements

• After reading break statement our compiler came out of loop and read the next statement after loop

(36)

Practice for statement

int number;

boolean flag = true;

number = 4;

for(int i=2; i<=number/2; i++) {

if( (number % i) == 0) {

flag = false;

break;

} }

if(flag)

System.out.println("This is Prime Number");

else

System.out.println("This is Not Prime Number");

(37)

Nested for Loops

• Like any other programming Language Java does allow loops

for(int i=0; i<3; i++) {

System.out.println(“i =”+i);

System.out.println();

for (int j=0; j<100; j++) { if(j==10) break;

System.out.println(“j =”+ j);

} System.out.println(); }

System.out.println(“Loops Completed”);

(38)

Extra Information on for Loops

• you can nest loops

• you can break execution and jump outside the loop

References

Related documents

Abbreviation: GCSE, generalized convulsive status epilepticus; TBI, Traumatic Brain injury; ‘‘Other’’ includes home health care, against medical advice *. p

Rajkumar and Swaroop (2008) measure the links between public spending, governance, and outcomes. They examine the role of governance–measured by the level of corruption and the

“You Stepped Out Of A Dream,” from the studio album, features Steve mixing it up on the brushes with a uniquely modern jazz approach in the context of a sax, bass, and

“Report Card on British Columbia's Secondary Schools: 2003 Edition” Studies in Educational Policy (Vancouver: Fraser Institute; March 2003): with Peter Cowley.. “Report Card

Less complicated to continue statement in while loop java tutorial, working with performance and switch statement block inside the program is possible execution flow control.. half

Overall evaluation of the data collected from the initial grain to the final beer illustrates individual grain characteristics can provide information about the malting and

“With Ruby and Rails we went from nothing to a live site from nothing to a live site in about in about 3 months 3 months. Only one person in the company had any prior Ruby

This tradition works, as it does for Marion, in two directions: looking forward from the Augustinian vantage point, Chrétien gestures towards Augustine’s role in the