Chapter 4 คำสั่งควบคุม (control statement) If statement Switch statement While loop and do-while loop For loop and for-each loop Break and continue 1.

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Advertisements

5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
CSCI S-1 Section 5. Deadlines for Problem Set 3 Part A – Friday, July 10, 17:00 EST Parts B – Tuesday, July 14, 17:00 EST Getting the code examples from.
Array Yoshi. Definition An array is a container object that holds a fixed number of values of a single type. The length of an array is established when.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops –For For Reading for this Lecture, L&L, Part of 5.8.
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
L EC. 03: C ONTROL STATEMENTS Fall Java Programming.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Introduction to Java. Main() Main method is where the program execution begins. There is only one main Displaying the results: System.out.println (“Hi.
Agenda Review User input Scanner Strong type checking Other flow-control structures switch break & continue Strings Arrays 2.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. CHAPTER 3: SELECTIONS 1.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
Switch Statement Is a selection control structure for multi-way branching. SYNTAX switch ( IntegralExpression ) { case Constant1 : Statement(s); // optional.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures II
Repetition Statements while and do while loops
August 6, 2009 Data Types, Variables, and Arrays.
Chapter 6. else-if & switch Copyright © 2012 Pearson Education, Inc.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Control Flow Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
S ystem P rogrammers' A ssociation for R esearching C omputer S ystems 4. Controlling Execution SPARCS JAVA Study.
SELF STUDY. IF STATEMENTS SELECTION STRUCTURE if selection statement if … else selection statement switch selection statement.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Java Methods 11/10/2015. Learning Objectives  Be able to read a program that uses methods.  Be able to write a write a program that uses methods.
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
A Introduction to Computing II Lecture 1: Java Review Fall Session 2000.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING Switch Statement.
1 More about Flow of Control. Topics Debugging Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement.
Array and String.
Loops and Logic. Making Decisions Conditional operator Switch Statement Variable scope Loops Assertions.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Slides by Evan Gallagher
Slides by Evan Gallagher
Chapter 4: Control Structures I
Control Structures.
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
TK1114 Computer Programming
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
Chapter 4: Control Structures I
Chapter 6 More Conditionals and Loops
CSS161: Fundamentals of Computing
The for-loop and Nested loops
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Object Oriented Programming
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Repetition Statements
More on iterations using
Presentation transcript:

Chapter 4 คำสั่งควบคุม (control statement) If statement Switch statement While loop and do-while loop For loop and for-each loop Break and continue 1

If statement มี syntax ดังนี้ if (booleanExpression) { statement (s) } หรือ if (booleanExpression) { statement (s) } else { statement (s) } 2

public class MainClass { public static void main(Str ing[] args) { int x = 9; if (x > 4) { // statements } } } public class MainClass { public static void main(String[] args) { int a = 3; if (a > 3) { // statements } else { // statements } } } 3

public class MainClass { public static void main(String[] args) { int a = 3; if (a > 3) a++; else a = 3; } } public class MainClass { public static void main(String[] arg s) { int a = 3, b = 1; if (a > 0 || b 2) System.out.println("a > 2"); else System.out.println("a < 2"); } } 4

public class MainClass { public static void main(String[] args) { int a = 3, b = 1; if (a > 0 || b 2) { System.out.println("a > 2"); } else { System.out.println("a < 2"); } } } } 5

Multi selection if (booleanExpression1) { // statements } else if (booleanExpression2) { // statements }... else { // statements } 6

Multi selection public class MainClass { public static void main(String[] args) { int a = 0; if (a == 1) { System.out.println("one"); } else if (a == 2) { System.out.println("two"); } else if (a == 3) { System.out.println("three"); } else { System.out.println("invalid"); } } } 7

public class MainClass { public static void main(String[] arg) { int a = 2; if (a == 0) { System.out.println("in the block"); if (a == 2) { System.out.println("a is 0"); } else { System.out.println("a is not 2"); } } else { System.out.println("a is not 0"); } } } 8

public class MainClass { public static void main(String[] arg) { int value = 8; int count = 10; int limit = 11; if (++value % 2 == 0 && ++count < limit) { System.out.println("here"); System.out.println(value); System.out.println(count); } System.out.println("there"); System.out.println(value); System.out.println(count); } } 9

public class MainClass { public static void main(String[] arg) { int value = 8; int count = 10; int limit = 11; if (++value % 2 != 0 || ++count < limit) { System.out.println("here"); System.out.println(value); System.out.println(count); } System.out.println("there"); System.out.println(value); System.out.println(count); } } 10

switch statement switch (expression) { case value_1 : statement (s); break; case value_2 : statement (s); break;... case value_n : statement (s); break; default: statement (s); } 11

public class MainClass { public static void main(String[] args) { int i = 1; switch (i) { case 1 : System.out.println("One."); break; case 2 : System.out.println("Two."); break; case 3 : System.out.println("Three."); break; default: System.out.println("You did not enter a valid value."); } } } 12

public class MainClass { public static void main(String[] args) { int choice = 2; switch (choice) { case 1: System.out.println("Choice 1 selected"); break; case 2: System.out.println("Choice 2 selected"); break; case 3: System.out.println("Choice 3 selected"); break; default: System.out.println("Default"); break; } } } Output : Choice 2 selected 13

public class MainClass { public static void main(String[] args) { char yesNo = 'N'; switch(yesNo) { case 'n': case 'N': System.out.println("No selected"); break; case 'y': case 'Y': System.out.println("Yes selected"); break; } } } Output : No selected 14

public class Main { public static void main(String[] args) { int i = 0; switch (i) { case 0: System.out.println("i is 0"); case 1: System.out.println("i is 1"); case 2: System.out.println("i is 2"); default: System.out.println("Free flowing switch example!"); } } } /* i is 0 i is 1 i is 2 Free flowing switch example! */ 15

public class Main { public static void main(String[] args) { int i = 0; switch (i) { case 0: int j = 1; switch (j) { case 0: System.out.println("i is 0, j is 0"); break; case 1: System.out.println("i is 0, j is 1"); break; default: System.out.println("nested default case!!"); } break; default: System.out.println("No matching case found!!"); } } } //i is 0, j is 1 16

while statement while (booleanExpression) { statement (s) } public class MainClass { public static void main(String[] args) { int i = 0; while (i < 3) { System.out.println(i); i++; } } } 17

public class MainClass { public static void main(String[] args) { int limit = 20; int sum = 0; int i = 1; while (i <= limit) { sum += i++; } System.out.println("sum = " + sum); } } sum =

public class MainClass { public static void main(String[] args) { double r = 0; while(r < 0.99d) { r = Math.random(); System.out.println(r); } } } 19

do-while statement do { statement (s) } while (booleanExpression); public class MainClass { public static void main(String[] args) { int i = 0; do { System.out.println(i); i++; } while (i < 3); } } Output :

public class MainClass { public static void main(String[] args) { int j = 4; do { System.out.println(j); j++; } while (j < 3); } } Output : 4 21

public class MainClass { public static void main(String[] args) { int limit = 20; int sum = 0; int i = 1; do { sum += i; i++; } while (i <= limit); System.out.println("sum = " + sum); } } Output : sum =

for statement for ( init ; booleanExpression ; update ) { statement (s) } เริ่มกำหนดค่า init ก่อนการทำคำสั่งรอบแรก. booleanExpression จะถูกประเมินความจริง ถ้าเป็น จริงจะทำ statement(s) คำสั่ง update จะถูกทำหลังจากมีการทำคำสั่งจน สิ้นสุด block. ค่าของ init, expression, และ update สามารถละได้ 23

คำสั่งภายใน block จะหยุดกระทำ เมื่อเกิดเงื่อนไขคื booleanExpression ถูกประเมินมีค่าเป็น เท็จ พบคำสั่ง break หรือ continue. เกิด runtime error 24

public class MainClas s { public static void m ain(String[] args) { for (int i = 0; i < 5; i ++) { System.out.print ln(i + " "); } } } public class MainClass { public static void mai n(String[] args) { int j = 0; for (; j < 3; j++) { System.out.println(j ); } // j is visible here } } 25

public class MainClass { public static void main( String[] args) { int k = 0; for (; k < 3;) { System.out.println(k) ; k++; } } } public class MainClass { public static void main(S tring[] args) { int m = 0; for (;;) { System.out.println(m) ; m++; if (m > 4) { break; } } } } 26

while (expression) {... } for ( ; expression; ) {... } 27

public class MainClass { public static void main( String[] args) { for (int i = 0; i < 8; i++) { System.out.println(" Hi."); } } } public class MainClass { public static void main(Str ing[] args) { int limit = 20; // Sum fro m 1 to this value int sum = 0; // Accumul ate sum in this variable for (int i = 1; i <= limit; i+ +) { sum = sum + i; } System.out.println("sum = " + sum); } } 28

public class Main { public static void main( String[] args) { for (;;) { System.out.println(" Hello"); break; } } } //Hello public class MainClass { public static void main(St ring[] arg) { int limit = 10; int sum = 0; for (int i = 1, j = 0; i <= li mit; i++, j++) { sum += i * j; } System.out.println(sum) ; } }

public class Main { public static void main(String[] args) { for (int i = 0, j = 1, k = 2; i < 5; i ++){ System.out.println("I : " + i + ",j : " + j + ", k : " + k); } } } /* I : 0,j : 1, k : 2 I : 1,j : 1, k : 2 I : 2,j : 1, k : 2 I : 3,j : 1, k : 2 I : 4,j : 1, k : 2 */ public class Main { public static void main( String[] args) { for (int i = 0, j = 0; i < 5 ; i++, j--) System.out.println("i = " + i + " j= " + j); } } /* i = 0 j= 0 i = 1 j= -1 i = 2 j= -2 i = 3 j= -3 i = 4 j= -4 */ 30

public class MainClass { public static void main(Stri ng[] arg) { int limit = 10; int sum = 0; for (int i = 1; i <= limit;) { sum += i++; } System.out.println(sum); } } public class MainClass { public static void main(Str ing[] arg) { int limit = 10; int sum = 0; int i = 1; for (; i <= limit;) { sum += i++; } System.out.println(sum); } } 55 31

public class MainClass { public static void main(Stri ng[] arg) { for (double radius = 1.0; r adius <= 2.0; radius += 0.2) { System.out.println("radiu s = " + radius + "area = " + M ath.PI * radius * radius); } } } output radius = 1.0 area = radius = 1.2 area = radius = 1.4 area = radius = area = radius = area = radius = area =

public class MainClass { public static void main(String[] ar gs) { long limit = 20L; long factorial = 1L; for (long i = 1L; i <= limit; i++) { factorial = 1L; for (long factor = 2; factor <= i; factor++) { factorial *= factor; } System.out.println(i + "! is " + f actorial); } } } 33

public class MainClass { public static void main(String[] arg s) { int i = 0; outer: for (; true;) { inner: for (; i < 10; i++) { System.out.println("i = " + i); if (i == 2) { System.out.println("continue" ); continue; } if (i == 3) { System.out.println("break"); i++; break; } if (i == 7) { System.out.println("continue outer"); i++; continue outer; } if (i == 8) { System.out.println("break outer") ; break outer; } for (int k = 0; k < 5; k++) { if (k == 3) { System.out.println("continue inn er"); continue inner; } } } } } } 34

for-each loop for(type itr-var : iterableObj) statement-block 35

public class MainClass { public static void main(String args[]) { int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for(int x : nums) { System.out.print(x + " "); x = x * 10; // no effect on nums } System.out.println(); for(int x : nums) System.out.print(x + " "); System.out.println(); } } 36

for (type identifier : iterable_expression) { // statements } public class MainClass { enum Season { spring, summer, fall, winter } public static void main(String[] args) { for (Season season : Season.values()) { System.out.println(" The season is now " + season); } } } 37

public class MainClass { public static void main(String args[]) { int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; // use for-each style for to display and sum the values for(int x : nums) { System.out.println("Value is: " + x); sum += x; } System.out.println("Summation: " + sum); } } 38

public class MainClass { public static void main(String[] arg) { char[] vowels = { 'a', 'e', 'i', 'o', 'u'}; for(char ch: vowels){ System.out.println(ch); } } } 39

public class MainClass { public static void main(String args[]) { int sum = 0; int nums[][] = new int[3][5]; // give nums some values for (int i = 0; i < 3; i++) for (int j = 0; j < 5; j++) nums[i][j] = (i + 1) * (j + 1); // use for-each for to display and sum the values for (int x[] : nums) { for (int y : x) { System.out.println("Value is: " + y); sum += y; } } System.out.println("Summation: " + sum); } } 40

break statement คำสั่ง break จะออกจาก loop โดยจะไม่ execute คำสั่งที่ เหลือของ statements. public class MainClass { public static void main(String[] args) { int i = 0; while (true) { System.out.println(i); i++; if (i > 3) { break; } } } } 41

public class MainClass { public static void main(String[] args) { int count = 50; for (int j = 1; j < count; j++) { if (count % j == 0) { System.out.println("Breaking!!"); break; } } } } 42

public class MainClass { public static void main(String[] args) { OuterLoop: for (int i = 2;; i++) { for (int j = 2; j < i; j++) { if (i % j == 0) { continue OuterLoop; } } System.out.println(i); if (i == 107) { break; } } } } 43

public class Main { public static void main(String args[]) { int len = 100; int key = 50; int k = 0; out: { for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { if (i == key) { break out; } k += 1; } } } System.out.println(k); } } 44

public class MainClass { public static void main(String[] args) { OuterLoop: for (int i = 2;; i++) { for (int j = 2; j < i; j++) { if (i % j == 0) { continue OuterLoop; } } System.out.println(i); if (i == 37) { break OuterLoop; } } } } 45

public class MainClass { public static void main(String args[]) { int sum = 0; int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Use for to display and sum the values. for (int x : nums) { System.out.println("Value is: " + x); sum += x; if (x == 5){ break; // stop the loop when 5 is obtained } } System.out.println("Summation of first 5 elements: " + sum); } } 46

continue statement จะหยุดทำคำสั่งในรอบนั้น แล้วกลับไปเริ่มต้น ทำงานรอบใหม่ public class MainClass { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 5) { continue; } System.out.println(i); } } } 47

public class MainClass { public static void main(String[] arg) { int limit = 10; int sum = 0; for (int i = 1; i <= limit; i++) { if (i % 3 == 0) { continue; } sum += i; } System.out.println(sum); } } 48

public class MainClass { public static void main(String[] args) { int limit = 20; int factorial = 1; OuterLoop: for (int i = 1; i 10 && i % 2 == 1) { continue OuterLoop; } factorial *= j; } System.out.println(i + "! is " + factorial); } } } 49

Java Input - Using Java Scanner Import java.util.Scanner; Scanner scan = new Scanner(System.in); String input = scan.nextLine(); Int num = scan.nextInt(); 50

ตัวแปรอาเรย์เบื้องต้น (Array Basics) เป็นชื่อของกลุ่มข้อมูลที่มีประเภทเดียวกัน ข้อมูลแต่ละตัวจะเรียกว่า สมาชิกอาเรย์ (array element) สมาชิกตัวแรกจะมีดัชนี (index) เป็น 0 51

ตัวอย่าง array public class MainClass { public static void main(String[] arg) { int[] intArray = new int[10]; for (int i = 0; i < 10; i++) { intArray[i] = 100; } for (int i = 0; i < 10; i++) { System.out.println(intArray[i]); } } } 52

การกำหนดค่า array โดย index public class MainClass { public static void main(String args[]) { int month_days[]; month_days = new int[12]; month_days[0] = 31; month_days[1] = 28; month_days[2] = 31; month_days[3] = 30; month_days[4] = 31; month_days[5] = 30; month_days[6] = 31; month_days[7] = 31; month_days[8] = 30; month_days[9] = 31; month_days[10] = 30; month_days[11] = 31; System.out.println("April has " + month_days[3] + " days."); } } 53

การกำหนด array แบบอื่นๆ int al[] = new int[3]; int[] a2 = new int[3]; char twod1[][] = new char[3][4]; เท่ากับ char[][] twod2 = new char[3][4]; int[] nums, nums2, nums3; // create three arr ays 54

Anonymous arrays new type[] {comma-delimited-list} public class MainClass { public static void main (String args[]) { int array1[] = {1, 2, 3, 4, 5}; for(int i: array1){ System.out.print (i+” “); } } } Output :

Length of array public class MainClass { public static void main(String[] arg) { int[] intArray = new int[10]; for (int i = 0; i < intArray.length; i++) { intArray[i] = 100; } for (int i = 0; i < intArray.length; i++) { System.out.print(intArray[i]+” “); } } }

public class MainClass { public static void main(String[] arg) { double[] data = new double[50]; // An array of 50 values of type double for (int i = 0; i < data.length; i++) { // i from 0 to data.length-1 data[i] = 1.0; } for (int i = 0; i < data.length; i++) { // i from 0 to data.length-1 System.out.println(data[i]); } } } 57

Array of character public class MainClass{ public static void main(String[] arg){ char[] message = new char[5]; java.util.Arrays.fill(message, 'A'); for(char ch: message){ System.out.print (ch+” “); } } } A A A A A 58

iterate over an array for (componentType variable: arrayName) import java.util.Arrays; public class MainClass { public static void main(String[] arg) { double[] data = new double[5]; // An array of 50 values of type double Arrays.fill(data, 1.0); // Fill all elements of data with 1.0 for (double d: data) { System.out.println(d); } } }

Change size public class MainClass { public static void main(String[] args) { int[] numbers = { 1, 2, 3 }; int[] temp = new int[4]; int length = numbers.length; for (int j = 0; j < length; j++) { temp[j] = numbers[j]; } numbers = temp; } } 60

Duplicate array public class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', ' n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } } 61