Java 程式設計初階 第 5 章:基本輸出入 & 流程控制

Similar documents
Java 程式設計初階 第 5 章:基本輸出入 & 流程控制

CC213

untitled

附录J:Eclipse教程

3.1 num = 3 ch = 'C' 2

JavaIO.PDF

untitled

内 容 简 介 本 书 是 一 本 关 于 语 言 程 序 设 计 的 教 材, 涵 盖 了 语 言 的 基 本 语 法 和 编 程 技 术, 其 中 包 含 了 作 者 对 语 言 多 年 开 发 经 验 的 总 结, 目 的 是 让 初 学 的 读 者 感 受 到 语 言 的 魅 力, 并 掌

Java

Microsoft Word - 01.DOC

全国计算机技术与软件专业技术资格(水平)考试

Java Access 5-1 Server Client Client Server Server Client 5-2 DataInputStream Class java.io.datainptstream (extends) FilterInputStream InputStream Obj

Spyder Anaconda Spyder Python Spyder Python Spyder Spyder Spyder 開始 \ 所有程式 \ Anaconda3 (64-bit) \ Spyder Spyder IPython Python IPython Sp

單步除錯 (1/10) 打開 Android Studio, 點選 Start a new Android Studio project 建立專案 Application name 輸入 BMI 點下 Next 2 P a g e

使 用 Java 语 言 模 拟 保 险 箱 容 量 门 板 厚 度 箱 体 厚 度 属 性 锁 具 类 型 开 保 险 箱 关 保 险 箱 动 作 存 取 款

概述

Python a p p l e b e a r c Fruit Animal a p p l e b e a r c 2-2

2009年3月全国计算机等级考试二级Java语言程序设计笔试试题

untitled

Fun Time (1) What happens in memory? 1 i n t i ; 2 s h o r t j ; 3 double k ; 4 char c = a ; 5 i = 3; j = 2; 6 k = i j ; H.-T. Lin (NTU CSIE) Referenc

Microsoft Word - ch04三校.doc

Chapter 9: Objects and Classes

javaexample-02.pdf

Chapter 9: Objects and Classes

1.JasperReport ireport JasperReport ireport JDK JDK JDK JDK ant ant...6

Excel VBA Excel Visual Basic for Application

Microsoft Word - 小心翼翼的二十一點N.doc

1: public class MyOutputStream implements AutoCloseable { 3: public void close() throws IOException { 4: throw new IOException(); 5: } 6:

2/80 2


四川省普通高等学校

untitled

Learning Java

新版 明解C++入門編

雲端 Cloud Computing 技術指南 運算 應用 平台與架構 10/04/15 11:55:46 INFO 10/04/15 11:55:53 INFO 10/04/15 11:55:56 INFO 10/04/15 11:56:05 INFO 10/04/15 11:56:07 INFO

EJB-Programming-4-cn.doc

PowerPoint 簡報

ACI pdf

FY.DOC

chp6.ppt

(TestFailure) JUnit Framework AssertionFailedError JUnit Composite TestSuite Test TestSuite run() run() JUnit

nooog

詞 彙 表 編 號 詞 彙 描 述 1 預 約 人 資 料 中 文 姓 名 英 文 姓 名 身 份 證 字 號 預 約 人 電 話 性 別 2 付 款 資 料 信 用 卡 別 信 用 卡 號 信 用 卡 有 效 日 期 3 住 房 條 件 入 住 日 期 退 房 日 期 人 數 房 間 數 量 入

《大话设计模式》第一章

The golden pins of the PCI card can be oxidized after months or years

untitled

使用MapReduce读取XML文件

C 1

6-1 Table Column Data Type Row Record 1. DBMS 2. DBMS MySQL Microsoft Access SQL Server Oracle 3. ODBC SQL 1. Structured Query Language 2. IBM

内 容 提 要 将 JAVA 开 发 环 境 迁 移 到 Linux 系 统 上 是 现 在 很 多 公 司 的 现 实 想 法, 而 在 Linux 上 配 置 JAVA 开 发 环 境 是 步 入 Linux 下 JAVA 程 序 开 发 的 第 一 步, 本 文 图 文 并 茂 地 全 程 指

CC213

Microsoft Word - 投影片ch03

第3章.doc

Microsoft Word - PHP7Ch01.docx

C/C++语言 - 分支结构

新・明解C言語入門編『索引』

Microsoft Word - 11.doc

1 Framework.NET Framework Microsoft Windows.NET Framework.NET Framework NOTE.NET NET Framework.NET Framework 2.0 ( 3 ).NET Framework 2.0.NET F

投稿類別:電子工程類

6 C51 ANSI C Turbo C C51 Turbo C C51 C51 C51 C51 C51 C51 C51 C51 C C C51 C51 ANSI C MCS-51 C51 ANSI C C C51 bit Byte bit sbit

Outline USB Application Requirements Variable Definition Communications Code for VB Code for Keil C Practice

BOOL EnumWindows(WNDENUMPROC lparam); lpenumfunc, LPARAM (Native Interface) PowerBuilder PowerBuilder PBNI 2

(京)新登字063号

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

Java 1 Java String Date

C++ 程式設計

mvc

Microsoft PowerPoint - OPVB1基本VB.ppt

穨control.PDF

Microsoft PowerPoint - Lecture7II.ppt

( CIP) /. :, ( ) ISBN TP CIP ( 2005) : : : : * : : 174 ( A ) : : ( 023) : ( 023)

C/C++ 语言 - 循环

PowerPoint Presentation

VB程序设计教程

<4D F736F F D B0D3B77EC3FEA7DEC3C0C476C1C9A5BFA6A1B8D5C3442DB57BA6A1B35DAD702DBEC7ACEC2E646F6378>

(6) 要 求 付 款 管 理 员 从 预 订 表 中 查 询 距 预 订 的 会 议 时 间 两 周 内 的 预 定, 根 据 客 户 记 录 给 满 足 条 件 的 客 户 发 送 支 付 余 款 要 求 (7) 支 付 余 款 管 理 员 收 到 客 户 余 款 支 付 的 通 知 后, 检

_汪_文前新ok[3.1].doc

任務二 : 產生 20 個有炸彈的磚塊, 放在隨機的位置編輯 Block 類別的程式碼 import greenfoot.; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) Write a description of class

RUN_PC連載_10_.doc

9, : Java 19., [4 ]. 3 Apla2Java Apla PAR,Apla2Java Apla Java.,Apla,,, 1. 1 Apla Apla A[J ] Get elem (set A) A J A B Intersection(set A,set B) A B A B

Microsoft Word - CPE考生使用手冊 docx

Microsoft Word - 投影片ch13

穨文件1

untitled

untitled

<4D F736F F D20BAF4BADEA457BDD2B1D0A7F75F4A415641B57BA6A1B2D52E646F63>

Java java.lang.math Java Java.util.Random : ArithmeticException int zero = 0; try { int i= 72 / zero ; }catch (ArithmeticException e ) { // } 0,

TwinCAT 1. TwinCAT TwinCAT PLC PLC IEC TwinCAT TwinCAT Masc

untitled

C语言的应用.PDF

提问袁小兵:

untitled

untitled

大 綱 背 景 解 決 之 道 文 獻 探 討 建 置 貝 氏 網 路 研 究 結 果 結 論 2

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

软件工程文档编制

OOP with Java 通知 Project 4: 4 月 18 日晚 9 点 关于抄袭 没有分数

Microsoft Word - Learn Objective-C.doc

科学计算的语言-FORTRAN95

Microsoft PowerPoint - ds-1.ppt [兼容模式]

Transcription:

Standard I/O & Flow Control

Outline 2 Standard I/O Branch if ~ else switch ~ case Loop For while do ~ while Interrupt Break continue Conclusion

Standard I/O 3 Definition: 將資料印到螢幕上 Java 標準輸出指令 System.out.println( 資料 ) 將資料印出後換行 System.out.print( 資料 ) 將資料印完後不換行

Standard Input 4 Method 1: Command line argument java TestArg I am happy

Example 5 package FlowControl; public class ArgumentInput public static void main(string[] args) System.out.println(args[0]); System.out.println(args[1]); System.out.println(args[2]);

Command Line 6 按下鍵盤的 windows key+r 開啟執行視窗, 並輸入 cmd.exe 執行命令提示字元

Compile 7 利用 cd 切換至專案 java 檔所在路徑 此專案 workspace 設定在桌面, 專案名為 Java_5, 且 Package 命名為 FlowControl 輸入以下指令進行 Compile javac -d. *.java

Execute 8 Execute java FlowControl.ArgumentInput I am happy Java FlowControl.ArgumentInput I am happy Class Package args[2] args[1] args[0]

Standard Input 9 Method 2: Stream I/O Input Data from Keyboard import java.io.*; class classname public static void main(string[] args]) throws IOException BufferedReader br = new BufferedReader (new InputStreamReader(System.in) ); String name = br.readline();

Flow Control 10 if: 單一條件 if else : 雙重條件 if else if else 多重條件

if ~ else 11 if (Condition) // true Statement 1 Statement 2 else // False Statement 1 Statement 2

Example 12 public class FlowControl_1 public static void main(string[] args) int balance = 2000; double rate = 0.05; if ( balance < 1000) System.out.println(" 餘額要是低於 1000 元, 沒有利息可計 "); System.out.println(" 您目前餘額現在有 " + balance + " 元 "); System.out.println(" 沒有利息可計 "); else//balance >= 1000 System.out.println(" 您目前餘額現在有 " + balance + " 元 "); System.out.println(" 您可得利息 " + (balance*rate) + " 元 ");

Example 13 class FlowControl_2 public static void main(string[] args) throws IOException BufferedReader br = new BufferedReader(new InputStreamReader(System.in) ); System.out.println("1. 餘額查詢 "); System.out.println("2. 轉帳服務 "); System.out.println("3. 轉接客服人員 "); System.out.print("\n 請輸入您需要的服務選項號碼 :"); String str = br.readline(); int select = Integer.parseInt(str); if (select == 1) System.out.println("\n 餘額正在查詢中, 請稍後 "); else if (select == 2) System.out.println("\n 詐欺集團猖獗, 小心轉帳被騙 "); else if (select == 3) System.out.println("\n 客服人員正在轉接中 "); else//select<1 or select>3 System.out.println(" 輸入選項有誤, 請查明再次輸入 ");

Results 14

Example 15 import java.io.*; public class FlowControl_3 public static void main(string[] args) throws IOException BufferedReader br = new BufferedReader(new InputStreamReader(System.in) ); System.out.print(" 請輸入密碼 :"); String pwd = br.readline(); if (pwd.equals("java2")) System.out.println(" 密碼正確 "); System.out.println(" 歡迎使用本系統 "); else System.out.println(" 密碼錯誤 "); System.out.println(" 請注意使用正確的大小寫 ");

Methods of String class 16 pwd.equals("java2") pwd.equalsignorecase("java2")

Example 17 import java.io.*; class FlowControl_4 public static void main(string[] args) throws IOException double pay; BufferedReader br = new BufferedReader(new InputStreamReader(System.in) ); System.out.print(" 請輸入購買杯數 :"); String str1 = br.readline(); int cup = Integer.parseInt(str1); pay = 10*cup; if (cup>=30) System.out.println("\n 應付金額為 " + (pay*0.7)); else if (cup>=20) System.out.println("\n 應付金額為 " + (pay*0.8)); else if (cup>=10) System.out.println("\n 應付金額為 " + (pay*0.9)); else System.out.println("\n 應付金額為 " + pay);

if ~ else (Example) 18 請製作一個傳入分數, 能夠印出 Grade A ~ F 的 Java Application java Grading 85 印出 Grade B 提示 : 放在 Grading 後面的 85, 會由 main 函式的 String[] args 部份接收 您可以用 args[0] 抓到這個 85 由於 args 宣告成字串, 所以 85 是文字的 85, 不是數字的 85 必須經過下列轉換後才能變成數字 int Score = Integer.parseInt(args[0]);

if ~ else (Example) 19 package FlowControl; public class Grading public static void main (String[] args) int Score = Integer.parseInt(args[0]); if (Score >= 90) System.out.println ("Grade A"); else if (Score >= 80) System.out.println ("Grade B"); else if (Score >= 70) System.out.println ("Grade C"); else if (Score >= 60) System.out.println ("Grade D"); else System.out.println ("Grade F");

switch ~ case 20 switch (expression) case value 1: ; break; case value 2: ; break; case value N: default:.. ; break; ; break;

switch ~ case 21 Case: case 後方只能接 byte / short / int / char 四種型態 如 :case 1: 或 case a : 不像 Visual Basic 的 select case, 可填入一個範圍, 此乃 Java switch ~ case 之限制 break; Break 指令可以阻止程式繼續往下執行, 並跳出整個 switch ~ case 結構 但有時您會希望程式可以繼續往下執行

Example 22 public class FlowControl_5 public static void main(string[] args) int select = 2; switch(select) case 1: System.out.println(" 你選擇了 1"); break; case 2: System.out.println(" 你選擇了 2"); break; case 3: System.out.println(" 你選擇了 3"); break; default: System.out.println(" 你選擇了其他號碼 "); System.out.println(" 程式結束 ");

Example 23 class FlowControl_6 public static void main(string[] args) char seat = 'A'; switch(seat) case 'A': System.out.println(" 你的艙等是頭等艙 "); break; case 'B': System.out.println(" 你的艙等是商務艙 "); break; case 'C': System.out.println(" 你的艙等是豪華經濟艙 "); break; case 'D': System.out.println(" 你的艙等是經濟艙 "); break; default: System.out.println(" 沒有座位 ");

What is the Result? 24 int a = 10; switch (a) case 5: System.out.println( num= 5 ); case 10: System.out.println( num=10 ); case 11: System.out.println( num=11 ); default: System.out.println( non num );

What is the Result? 25 Ans num=10 num=11 non num 特別注意, 要有 break

for 26 Format: for ( 起始條件 ; 執行條件 ; 遞增值 ) Example: public class ForExample_1 public static void main(string[] args) int i; for (i=1; i <=10; i++) System.out.println ("i = " + i);

for 27 Loop end: public class ForExample_2 public static void main (String[] args) int i; for (i=1; i <=10; i++) System.out.println ("i = " + i); System.out.println ("After loop, i = " + i);

for 28 起始條件, 執行條件, 遞增值內部不一定只能有一個變數 : public class ForExample_3 public static void main (String[] args) for (int i=0, j=20; i<=20 && j>=1; i+=2, j-=2) System.out.println("i = " + i + " j = " + j);

while 29 Format while (condition) instruction; Example public class WhileExample public static void main (String[] args) int i=1; while (i++<=10) System.out.println("i = " + i); 不知道要讓迴圈執行幾次才要停止的時候使用

do ~ while 30 Format do Instruction; while (condition); Example 計算所有平方值小於等於 100 的數字, 並將該數字及其平方值印出來

do ~ while 31 public class DoWhileExample public static void main(string[] args) int i=0, j; do i++; j = i * i; System.out.println(i + "*" + i + "=" + j); while(j<100);

break 32 Function 中斷目前區塊 (block) 的流程 Format break [ 跳躍標籤 ] 其中 break + 跳躍標籤的情況常用於一口氣要跳出兩層以上的巢狀迴圈 否則僅跳出目前區塊的迴圈而已

Example for break 33 以下範例會在內圈變數 j == 7 時停止, 而只印出 1~6 十次 public class BreakExample_1 public static void main(string[] args) int i, j; for (i=1; i<=10; i++) for (j=1; j<=10; j++) if (j==7) break; System.out.print("j = " + j + " "); System.out.println(""); System.out.println("Total Loop of i = " + (i-1));

Example 2 for break 34 以下範例會在內圈變數 j == 7 時停止, 而只印出 1~6 一次 public class BreakExample_2 public static void main(string[] args) int i, j; outer: for (i=1; i<=10; i++) for (j=1; j<=10; j++) if (j==7) break outer; System.out.print("j = " + j + " "); System.out.println(""); System.out.println("Total Loop of i = " + (i-1));

continue 35 Function 可以跳過這一次的迴圈不執行, 直接從下一個迴圈開始執行 Format continue [ 跳躍標籤 ];

Example for continue 36 以下範例會跳過內圈變數 j == 7 那一圈, 而印出 1~6, 8~10 十次 public class BreakExample_3 public static void main(string[] args) int i, j; for (i=1; i<=10; i++) for (j=1; j<=10; j++) if (j==7) continue; System.out.print("j = " + j + " "); System.out.println(""); System.out.println("Total Loop of i = " + (i-1));

Results 37

Conclusion 38 Java standard output Java standard input Instructions: if ~ else switch ~ case for while do ~ while break & continue

Bubble Sort

Introduction 40 Bubble Sort( 氣泡排序 ) 是最容易理解和實作的排序演算法之一 重複地走訪 (Traversal) 要排序的陣列, 一次比較兩個相鄰元素的數值大小, 若值的順序錯誤則對它們進行交換的動作 重複上述步驟直到無交換動作, 此時該陣列已完成排序 Step 1. 1 5 3 4 2 Step 2. 1 5 3 4 2 Step 3. 1 3 5 4 2 Step 4. 1 3 4 5 2 Step 5. 1 3 4 2 5 Step 6. 1 3 4 2 5 Step 7. 1 3 4 2 5

Time Complexity 41 (Worst Case) 若有一筆長度為 n 的陣列, 該陣列的數值是由大到小排序, 若使用 Bubble Sort 進行由小到大排序, 則每次的走訪需執行 n 1 n 2 1 次交換, 其總次數如下 : f n = n 1 + n 2 + + 1 = n n 1 2 = n2 n 2 由上式可知當陣列長度增加時, 成長最快的是 Complexity) Big-O 為 O f n = O(n 2 ) n 2, 其時間複雜度 (Time

Example (1/2) 42 public class BubbleSort public static void main(string[] args) int[] A = 1, 5, 3, 4, 2; int i, j, k; int count = 0;// 進行了幾次交換的動作 // 印出原先的順序 System.out.print("Original A = "); for(i=0; i<a.length; i++) System.out.print(A[i] + " "); System.out.println(""); for (i = 0; i < ( A.length - 1 ); i++) for (j = 0; j < ( A.length - i - 1 ); j++)

Example (2/2) 43 //swap if (A[j] > A[j+1]) int tmp = A[j]; A[j] = A[j+1]; A[j+1] = tmp; count++; // 印出該次排序後的資料 System.out.print("Bubble sort = "); for(k=0; k<a.length; k++) System.out.print(A[k] + " "); System.out.println(""); System.out.println(" 總共進行了 " + count + " 次的交換 ");

Results 44