Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II.

Slides:



Advertisements
Similar presentations
Introduction to Java Programming Lecture 10 Method Benefits, Declaring, and Calling Methods.
Advertisements

1 生物計算期末作業 暨南大學資訊工程系 2003/05/13. 2 compare f1 f2  只比較兩個檔案 f1 與 f2 ,比完後將結果輸出。 compare directory  以兩兩比對的方式,比對一個目錄下所有檔案的相 似程度。  將相似度很高的檔案做成報表輸出,報表中至少要.
Divide-and-Conquer. 什麼是 divide-and-conquer ? Divide 就是把問題分割 Conquer 則是把答案結合起來.
Chapter 10 馬可夫鏈 緒言 如果讀者仔細觀察日常生活中所發生的 諸多事件,必然會發現有些事件的未來 發展或演變與該事件現階段的狀況全然 無關,這種事件稱為獨立試行過程 (process of independent trials) ;而另一些 事件則會受到該事件現階段的狀況影響。
: Arrange the Numbers ★★★☆☆ 題組: Contest Archive with Online Judge 題號: 11481: Arrange the Numbers 解題者:李重儀 解題日期: 2008 年 9 月 13 日 題意: 將數列 {1,2,3, …,N}
Introduction to Java Programming Lecture 13 Classes I OO Programming.
: A-Sequence 星級 : ★★☆☆☆ 題組: Online-judge.uva.es PROBLEM SET Volume CIX 題號: Problem D : A-Sequence 解題者:薛祖淵 解題日期: 2006 年 2 月 21 日 題意:一開始先輸入一個.
1 Q10276: Hanoi Tower Troubles Again! 星級 : ★★★ 題組: Online-judge.uva.es PROBLEM SET Volume CII 題號: Q10276: Hanoi Tower Troubles Again! 解題者:薛祖淵 解題日期: 2006.
Teacher : Ing-Jer Huang TA : Chien-Hung Chen 2015/6/3 Course Embedded Systems : Principles and Implementations Weekly Preview Question CH3.5 ~ CH /10/31.
期末專題 - 吊人頭遊戲 第 35 組 組員 : 電機系 49841XXXX XXX 電機系 49841OOOO OOO.
What is static?. Static? 靜態 ? class Test { static int staticX; int instanceX; public Test(int var1, int var2) { this.staticX = var1; this.instanceX =
五小專案 黃詩晴 章乃云. 目錄 計算機 智慧盤 拼圖 記憶大挑戰 數學題庫 心得 參考文獻.
亂數產生器安全性評估 之統計測試 SEC HW7 姓名:翁玉芬 學號:
: OPENING DOORS ? 題組: Problem Set Archive with Online Judge 題號: 10606: OPENING DOORS 解題者:侯沛彣 解題日期: 2006 年 6 月 11 日 題意: - 某間學校有 N 個學生,每個學生都有自己的衣物櫃.
JAVA 程式設計與資料結構 第二章 JAVA 程式基本概念及操作. 第一個程式 /* * 這是第一個程式 (FirstP.java) */ class FirstP{ public static void main(String args[]){ System.out.println("Whatever.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
1 Introduction to Java Programming Lecture 7 Flow Control : Boolean expressions and the if statement.
McGraw-Hill/Irwin © 2003 The McGraw-Hill Companies, Inc.,All Rights Reserved. 肆 資料分析與表達.
 Pearson Education, Inc. All rights reserved break and continue Statements Break and continue statements – Alter flow of control break.
1 Introduction to Java Programming Lecture 4 Using JOptionPane Spring 2008.
Introduction to Java Programming Lecture 17 Abstract Classes & Interfaces.
第 5 章 深入 Response 物件 製作. 網頁的轉向與強制輸出 - 讓網頁轉彎的 Redirect 敘述 運用 Response 物件的 Redirect 方法,將瀏覽器顯 示的網頁,導向至其他網頁,語法如下: Response.Redirect 網頁路徑與名稱 此網頁路徑與名稱  若是導向到同一台.
第 6 章 迴圈結構 6-1 計數迴圈 6-1 計數迴圈 6-2 條件迴圈 6-2 條件迴圈 6-3 巢狀迴圈 6-3 巢狀迴圈 6-4 While/End While 迴圈 6-4 While/End While 迴圈 6-5 跳出與繼續迴圈 6-5 跳出與繼續迴圈 6-6 錯誤處理 6-6 錯誤處理.
Introduction to Java Programming Lecture 10 Array I Declaring, Creating, and Initializing Arrays.
Matlab Assignment Due Assignment 兩個 matlab 程式 : Eigenface : Eigenvector 和 eigenvalue 的應用. Fractal : Affine transform( rotation, translation,
類別函式庫. Java Bean 一個單獨的 AWT 元件都是一個 bean. Java Bean 也有一個 bean 的 class 可繼承, 但是並不強 迫一定要繼承. Bean 的結構 Properties 屬性 : 描述 bean 的屬性 如顏色, 大小,label 等. 透過一對 methods.
: Happy Number ★ ? 題組: Problem Set Archive with Online Judge 題號: 10591: Happy Number 解題者:陳瀅文 解題日期: 2006 年 6 月 6 日 題意:判斷一個正整數 N 是否為 Happy Number.
: Fast and Easy Data Compressor ★★☆☆☆ 題組: Problem Set Archive with Online Judge 題號: 10043: Fast and Easy Data Compressor 解題者:葉貫中 解題日期: 2007 年 3.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
: Problem A : MiniMice ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11411: Problem A : MiniMice 解題者:李重儀 解題日期: 2008 年 9 月 3 日 題意:簡單的說,題目中每一隻老鼠有一個編號.
: Ahoy, Pirates! ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11402: Ahoy, Pirates! 解題者:李重儀 解題日期: 2008 年 8 月 26 日 題意:有一個海盜島有 N 個海盜,他們的編號 (id)
: Count DePrimes ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11408: Count DePrimes 解題者:李育賢 解題日期: 2008 年 9 月 2 日 題意: 題目會給你二個數字 a,b( 2 ≦ a ≦ 5,000,000,a.
: Multisets and Sequences ★★★★☆ 題組: Problem Set Archive with Online Judge 題號: 11023: Multisets and Sequences 解題者:葉貫中 解題日期: 2007 年 4 月 24 日 題意:在這個題目中,我們要定義.
公司加入市場的決定. 定義  平均成本 = 總成本 ÷ 生產數量 = 每一單位產量所耗的成本  平均固定成本 = 總固定成本 ÷ 生產數量  平均變動成本 = 總變動成本 ÷ 生產數量.
Marble on tree ★★★☆☆ 題組: ACM Programming Contest World Finals, 1998 題號: Marble on tree 解題者:呂為萱 解題日期: 2011 年 3 月 16 日 題意: 有 n 個箱子,被擺放在 rooted.
資料結構實習-一 參數傳遞.
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2008.
: Problem G e-Coins ★★★☆☆ 題組: Problem Set Archive with Online Judge 題號: 10306: Problem G e-Coins 解題者:陳瀅文 解題日期: 2006 年 5 月 2 日 題意:給定一個正整數 S (0
: GCD - Extreme II ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11426: GCD - Extreme II 解題者:蔡宗翰 解題日期: 2008 年 9 月 19 日 題意: 最多 20,000 組測資,題目會給一個數字.
資料結構實習-二.
: Expect the Expected ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11427: Expect the Expected 解題者:李重儀 解題日期: 2008 年 9 月 21 日 題意:玩一種遊戲 (a game.
Linguistics phonetic symbols. 先下載 IPA 字型檔案,執行安裝。 由於這個程式的字型目錄設定錯誤, 所以等重新開機時就會發現字型消失。 所以必須根據以下步驟來讓 Windows 加入 IPA 字型。
: Function Overloading ★★★☆☆ 題組: Problem Set Archive with Online Judge 題號: 11032:Function Overloading 解題者:許智祺 解題日期: 2007 年 5 月 8 日 題意:判對輸入之數字是否為.
1 Introduction to Java Programming Lecture 4 Using JOptionPane Spring 2010.
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2009.
5 重複迴圈 5.1 增減運算符號 增量運算符號 減量運算符號
Introduction to Java Programming Lecture 8 Flow Control : while do-while and for loops.
第 6 章 迴圈結構 6-1 計數迴圈 6-1 計數迴圈 6-2 條件迴圈 6-2 條件迴圈 6-3 巢狀迴圈 6-3 巢狀迴圈 6-4 While/End While 迴圈 6-4 While/End While 迴圈 6-5 跳出迴圈 6-5 跳出迴圈 6-6 VB.NET 的錯誤處理 6-6 VB.NET.
Teacher : Ing-Jer Huang TA : Chien-Hung Chen 2015/6/30 Course Embedded Systems : Principles and Implementations Weekly Preview Question CH7.1~CH /12/26.
: Wine trading in Gergovia ★★☆☆☆ 題組: Contest Volumes with Online Judge 題號: 11054: Wine trading in Gergovia 解題者:劉洙愷 解題日期: 2008 年 2 月 29 日 題意:在 Gergovia.
Introduction to Java Programming Lecture 12 Method Benefits, Declaring, and Calling Methods.
1 Introduction to Java Programming Lecture 3 Mathematical Operators Spring 2008.
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2010.
What is static? CS340100, NTHU Yoshi. Static? 靜態 ? class Test { static int staticX; int instanceX; public Test(int var1, int var2) { this.staticX = var1;
:Count the Trees ★★★☆☆ 題組: Problem Set Archive with Online Judge 題號: 10007:Count the Trees 解題者:楊家豪 解題日期: 2006 年 3 月 題意: 給 n 個點, 每一個點有自己的 Label,
Chapter 3 Control Statements F Selection Statements –Using if and if...else –Nested if Statements –Using switch Statements –Conditional Operator F Repetition.
: Finding Paths in Grid ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11486: Finding Paths in Grid 解題者:李重儀 解題日期: 2008 年 10 月 14 日 題意:給一個 7 個 column.
幼兒行為觀察與記錄 第八章 事件取樣法.
1 Introduction to Java Programming Lecture 3 Mathematical Operators Spring 2009.
: How many 0's? ★★★☆☆ 題組: Problem Set Archive with Online Judge 題號: 11038: How many 0’s? 解題者:楊鵬宇 解題日期: 2007 年 5 月 15 日 題意:寫下題目給的 m 與 n(m
McGraw-Hill/Irwin © 2003 The McGraw-Hill Companies, Inc.,All Rights Reserved. 肆 資料分析與表達.
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 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
C++ Control Structures 程式的控制、運算、判斷跟你之前學過的程式語言是類 似的,所以這裡我們只用程式碼來說明。 你應該而且必須能看得懂這些程式 !!
Chapter 4 – C Program Control
Java Tutorial /10/21. Java Resource Java SDK –Download from –Install Jdk windows-i586.exe –
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Chapter 5: Control Structures II
Speaker: Liu Yu-Jiun Date: 2009/4/15
Presentation transcript:

Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

Basic while Loop int sum = 0; int i = 1; while (i <= 7) { sum += i; i++; } 1. Initialization 2. Test Condition 4. Update: In this case, you can use either the pre or post increment operator. 3. Loop body sumi Example : Compute the sum n. (for n=7)

左右兩個程式結果有何不同 int n = 7; int sum = 0; int i = 1; while (i <= n) { sum += i; i++; } System.out.println(sum); (if n = 7, output = 28) int n = 7; int sum = 0; int i = 1; while (i <= n) { i++; sum += i; } System.out.println(sum); (if n = 7, output = ?)

可能會犯的錯誤 : ? int n = 7; int sum = 0; int i = 1; while (i < n) { sum += i; i++; } System.out.println(sum); 廻圈很容易就會多做或少做一次, 在寫判斷時要仔細想清楚

另一個可能會犯的錯誤 int n = 7; int sum = 0; int i = 1; while (i <= n) sum += i; i++; System.out.println(sum); (if n = 7, output = ?)

這也是常犯的錯誤 int n = 7; int sum = 0; int i = 1; while (i <= n); { sum += i; i++; } System.out.println(sum); ( 如果 n = 7, 結果會顯示什麼 ?)

Basic do/while Loop Example : Compute the sum n. (for n=7) int sum = 0; int i = 1; do { sum += i; i++; } while (i <= n); System.out.println(sum); 1 Initialization 4 Test Condition 2 Loop body 3 Update: In this case, you can use either the pre or post increment operator.

利用廻圈來檢查使用者的輸入 Scanner scan = new Scanner(System.in); System.out.println(" 請輸入 1 到 10 之間的數字 :"); int num = scan.nextInt(); Scanner scan = new Scanner(System.in); int num do{ System.out.println(" 請輸入 1 到 10 之間的數字 :"); num = scan.nextInt(); }while(num 10); 如果使用者輸入了範圍之外的數字呢 ?

9 Basic For Loop Syntax For loops are good for creating definite loops. int n = 7; int sum = 0; for (int i =1; i <= n; i++) sum += i; System.out.println(sum); 1. initialization 2. Test Condition 4. Update: Update the value. Note that each section is separated by a semicolon. 3. Loop body

10 for Loop Variations Update may be negative: for (i = 100; i >= 1; i--) –This counts from 100 to 1. Update may be greater than 1: for (i = 100; i >= 5; i -= 5) –This counts from 100 to 5 in steps of 5

Arithmetic expressions –Initialization, loop-continuation, and increment can contain arithmetic expressions. If x equals 2 and y equals 10 for ( j = x; j <= 4 * x * y; j += y / x ) is equivalent to for ( j = 2; j <= 80; j += 5 ) for Loop Variations

12 The Comma Operator Commas known here as comma operators by using commas, you can put more than one statement in any expression for (i = 100, y = 0; i >= 1; i--) or for (i = 0, j = 0; j + i <= 10; j++, i++) Commas known here as comma operators

13 幾個需要注意的事情 不要使用 float 或 double 當廻圈的判斷或計數的變數 分清楚, 跟 ; 在 for 廻圈中的功用 跟 if, while 一樣,在判斷後立刻加上 ; 會產生跟預期 不同的結果 int n = 7; int sum = 0; for (int i =1; i <= n; i++); sum += i; 分號的影響是什麼

Loop types Indefinite Loop ( 不定次數的迴圈 ) : –You do not know ahead of time how many times your loop will execute. –For example, you do not know how many books a person might order. Definite Loop ( 固定次數的迴圈 ) : –You know exactly how many times you want the loop to execute. –not at compile time necessarily

Counter- and Sentinel-controlled repetition Counter Controlled Repetition : ( 利用 “ 計數器 ” 來控制迴圈是否繼續執行,用於固定次數 迴圈 ) –Simply means that we use a counter to tell you when to stop repeating a statement or group of statements However, what if we want the user to decide when to end the program? –Use a sentinel (sentinel control, user control) ( 如果要由程式使用者控制,利用 sentinel 或 flag ,其 實就是設一個控制的變數,利用設定、判斷此變數為 1 或 0 (true or false) 來控制迴圈是否繼續執行 )

Indefinite Loop : A while example // TestWhile.java: Test the while loop import javax.swing.JOptionPane; public class TestWhile { public static void main(String[ ] args) { int data; int sum = 0; // Read an initial data String dataString = JOptionPane.showInputDialog(null, "Enter an int value, \nthe program exits if the input is 0“); data = Integer.parseInt(dataString);

// Keep reading data until the input is 0 while (data != 0) { sum += data; // Read the next data dataString = JOptionPane.showInputDialog(null, "Enter an int value, \nthe program exits if the input is 0" ); data = Integer.parseInt(dataString); } JOptionPane.showMessageDialog(null, "The sum is " + sum); System.exit(0); }

Which Loop to Use? The three forms of loop statements, while, do, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. I recommend that you use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.

Nested loops 廻圈中的廻圈 Example: How many times is JAVA printed out? for (int i = 1; i <= 7; i++) for (int j = 1; j <= 7; j++) System.out.println("JAVA"); for (int i = 1; i <= 7; i++) for (int j = i; j <= 7; j++) System.out.println("JAVA");

break and continue

break We have seen the keyword break used in a switch statement: switch (userInput) { case 1: userInput++; break; } You can also use break inside of a for, while or do/while loop to immediately exit from the loop.

Example of break use // TestBreak.java: Test the break keyword in the loop public class TestBreak { /** Main method */ public static void main(String[] args) { int sum = 0; int item = 0; while (item < 5) { item ++; sum += item; if (sum >= 6) break; } System.out.println("The sum is " + sum); }

continue Continue is a statement which can be used inside a for, while or do/while loop in order to skip the rest of the remaining code in the loop, and start the next iteration.

Example of continue // TestContinue.java: Test the continue keyword public class TestContinue { /** Main method */ public static void main(String[] args) { int sum = 0; int item = 0; while (item < 5) { item++; if (item == 2) continue; sum += item; } System.out.println("The sum is " + sum); }