1. 程式人生 > >java初學 流程控制語句 if…else switch ...

java初學 流程控制語句 if…else switch ...

  1. 順序語句

語句:使用分號分隔的程式碼稱作為一個語句。

 

注意:沒有寫任何程式碼只是一個分號的時候,也是一條語句,稱作空語句。

 

順序語句就是按照從上往下的順序執行的語句。

  1. 判斷(ifelse)

在我們找工作的過程中,要求兩年工作經驗以上且年齡超過30歲。

什麼是判斷語句:用於判斷的語句叫判斷語句。

1.格式一  

if(判斷條件){

如果符合條件執行的程式碼;

執行的程式碼塊1;

執行的程式碼塊2;

……………….;

執行的程式碼塊n;

}

 

 

 

 

 

練習:提示使用者輸入一個整數。如果該整數是5的倍數,列印“5的倍數”如果是2的倍數列印“2的倍數”

提示:為了便於讓使用者輸入資料,我們使用Scanner這個類,固定用法Scanner sc=new Scanner(System.in); 該類需要匯入包import java.util.Scanner;

int nextInt = sc.nextInt();獲取使用者輸入的數字

import java.util.Scanner;

public class Demo9 {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

int nextInt = sc.nextInt();

if(nextInt%5==0){

System.out.println("5的倍數");

}

if(nextInt%2==0){

System.out.println("2的倍數");

}

}

}

 

2.格式二

if(判斷條件){

執行的程式碼塊1;

執行的程式碼塊2;

……………….;

執行的程式碼塊n;

}else{

執行的程式碼塊1;

執行的程式碼塊2;

……………….;

執行的程式碼塊n;

}

 

 

案例:判斷一個整數是奇數還是偶數

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("請輸入一個整數:");

int nextInt = sc.nextInt();

if (nextInt % 2 == 0) {

System.out.println("是偶數");

} else {

System.out.println("是奇數");

}

System.out.println("over");

}

同樣道理如果花括號中只有一條語句,那麼花括號可以省略不寫,初學者不推薦省略。

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("請輸入一個整數:");

int nextInt = sc.nextInt();

if (nextInt % 2 == 0)

System.out.println("是偶數");

else

System.out.println("是奇數");

 

System.out.println("over");

}

 

觀察發現if else語句有點類似於三元運算子.其實三元運算子是if else 的一種簡寫格式.

Public static void main(String[] args) {

int x = 0, y = 1, b;

// if else 語句

if (x > y) {

b = x;

} else {

b = y;

}

System.out.println(b);// 1

// 3元運算

b = x > y ? x : y;

System.out.println(b); // 1

}

這兩種格式是一樣的。if else 結構 簡寫格式: 變數 = (條件表示式)?表示式1:表示式2;

三元運算子:

好處:可以簡化if else程式碼。

弊端:因為是一個運算子,所以運算完必須要有一個結果。

 

3. 格式三

if(判斷條件1){

執行的程式碼塊1;

}else  if(判斷條件2){

執行語句;

}else if(判斷條件3){

執行語句;

}

 

需求: 根據使用者定義的數值不同,列印對應的星期英文。if 只能進行一層判斷,if else 只能進行兩層判斷,那麼需要多層判斷時呢?星期可是有7個數的。如何設計程式碼?

使用if 語句

public static void main(String[] args) {

int x = 8;

if (x == 1) {

System.out.println("星期一");

}

if (x == 2) {

System.out.println("星期二");

}

if (x == 3) {

System.out.println("星期三");

}

}

如果這樣設計的話,第一個if語句執行完畢後,第二個語句仍會執行(去判斷),是一個順序結構.那麼事實上當前定義的星期之後會有一個.假如,第一個已經符合條件,那麼剩餘的執行就沒有意義了。屬於邏輯錯誤。

使用if else ,如果使用者輸入的是7以外的資料,那麼怎麼處理?就需要使用else 了

方案2:使用if else if語句

public static void main(String[] args) {

int x = 8;

if (x == 1) {

System.out.println("星期一");

} else if (x == 2) {

System.out.println("星期二");

} else if (x == 3) {

System.out.println("星期三");

} else if (x == 4) {

System.out.println("星期四");

} else if (x == 5) {

System.out.println("星期五");

} else if (x == 6) {

System.out.println("星期六");

} else if (x == 7) {

System.out.println("星期日");

} else {

System.out.println("請輸入數字1-7");

}

}

注意:

public static void main(String[] args) {

int x = 5;

if (x == 1) {

System.out.println("1");

}

if (x == 2) {

System.out.println("2");

}

if (x == 3) {

System.out.println("3");

} else {

System.out.println("4"); // 4

}

}

該if 語句不是一個整體,第一個if 是一個語句,第二個又是一個語句,最後的if else 又是一個語句。

if語句特點

  1. 第二種格式與三元運算子的區別:三元運算子運算完要有值出現。好處是:可以寫在其他表示式中。
  2. 條件表示式無論寫成什麼樣子,只看最終的結構是否是true 或者 false。

練習1: 根據使用者輸入的月份,打印出月份所屬的季節.

練習2: 根據使用者輸入的成績,進行評級,根據學生考試成績劃分ABCD   

練習1:

public static void main(String[] args) {

int x = 1;

if (x == 3) {

System.out.println("spring");

} else if (x == 4) {

System.out.println("spring");

}

}

 

仔細觀察:發現if和else if要執行的語句是一樣的,可不可以合併呢。當然是可以的。怎麼合併?使用邏輯運算子,那麼使用哪個邏輯運算子呢, &肯定不行。需要全部為真才為真,月份是不可能同時滿足的 那麼使用|連線符號即可。意思只要其中一個為真,就為真。另外可以使用短路功能。

public static void main(String[] args) {

int x = 1;

if (x == 3 || x == 4 || x == 5) {

System.out.println("spring");

} else if (x == 6 || x == 7 || x == 8) {

System.out.println("Summer");

 

} else if (x == 9 || x == 10 || x == 11) {

System.out.println("autumn");

} else {

System.out.println("Winter");

} else {

System.out.println("月份不存在");

}

}

練習2

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("請輸入考試分數:");

double score = sc.nextDouble();

char grade;

if (score >= 90.0)

grade = 'A';

else if (score >= 80.0)

grade = 'B';

else if (score >= 70.0)

grade = 'C';

else if (score >= 60.0)

grade = 'D';

else

grade = 'F';

System.out.println("你的成績是:" + grade);

 

}

 

If語句常見的錯誤

1.忘記必要的括號:如果程式碼塊中只有一條語句的時候,可以省略花括號,但是當花括號將多條語句擴在一起時,花括號就不能在省略。

double radius = 4;

double area;

if (radius >= 0)

area = radius * radius * 3.14;

System.out.println("The area " + " is " + area);

double radius = 4;

double area;

if (radius >= 0) {

area = radius * radius * 3.14;

System.out.println("The area " + " is " + area);

}

雖然程式碼一樣多,但是第一個會編譯報錯(area沒有出初始化),第二個正常執行。就是因為少了花括號。所以一定要仔細。

2.if語句後出現分號

double radius = 0;

double area;

if (radius > 0); {

area = radius * radius * 3.14;

System.out.println("The area " + " is " + area);

}

注意:這是一個邏輯錯誤,編譯和執行都不會報錯,只是不會出現想要的結果。

相當於判斷符合條件後,執行一個空語句。

double radius = 0;

double area;

if (radius > 0){}{

area = radius * radius * 3.14;

System.out.println("The area " + " is " + area);

}

 

判斷閏年

1:什麼是閏年?可以被4整除不能被100整除,或者可以被400整除,那麼這一年就是閏年(leap year)

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("請輸入年份:");

 

int year = sc.nextInt();

// 判斷年份能否被4整除

boolean isLeapYear = (year % 4 == 0);

// 年份能被4整除,並且不能被100整除並且使用&&and

isLeapYear = isLeapYear && (year % 100 != 0);

// 年份或者能夠被400整除

isLeapYear = isLeapYear || (year % 400 == 0);

if (isLeapYear) {

System.out.println(year + "是閏年!");

}

// 簡寫格式;

if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {

System.out.println(year + "是閏年!");

}

}

 

  1. 選擇判斷語句(switch)

switch語句

格式:

switch(表示式)

{

case 取值1:

執行語句;

break;

case 取值2:

執行語句;

break;

…...

default:

執行語句;

break;

}

switch語句特點:

    1,switch語句選擇的型別只有四種:byte,short,int , char。

2,case之間與default沒有順序。先判斷所有的case,沒有匹配的case執行

default。

3,switch語句停止的條件是遇到了break關鍵字或者結束switch語句的大括號。

4,如果匹配的case或者default沒有對應的break,那麼程式會繼續向下執行,運

行可以執行的語句,直到遇到break或者switch結尾結束。

5,switch case中的值必須要與switch表示式的值具有相同的資料型別。而且case後跟的值必須是常量,不能跟變數。

 

案例:

public static void main(String[] args) {

int x = 3;

switch (x) {

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("ok");

break;

}

}

case 就像選擇題的答案之一。 break 就是如果該答案正確那麼就可以跳出switch 了,意思就是說 已經找出了正確的答案了。那麼這道題也就做完了。如果 case 沒有匹配接著進行下一個case 匹配,直到匹配為止。 最後如果都沒有匹配上,那麼 switch 給提供了一個預設的答案,就是 default。

注意: case後跟的是冒號:

每個case中的執行語句一定要加break;

練習:

需求2:根據用於指定的月份,列印該月份所屬的季節.

一旦case匹配,就會順序執行後面的程式程式碼,而不管後面的case是否匹配,直到遇見break,利用這一特性可以讓好幾個case執行統一語句.

345 spring   678 sunmer 9 10 11  autumn  12 1 2 winter

public static void main(String[] args) {

int x = 3;

switch (x) {

case 3:

case 4:

case 5:

System.out.println("spring");

break;

case 6:

case 7:

case 8:

System.out.println("sunmer");

break;

case 9:

case 10:

case 11:

System.out.println("autumn");

break;

case 12:

case 0:

case 1:

System.out.println("winter");

default:

System.out.println("ok");

break;

}

}

 

練習:char 型別在switch 中的使用.

public static void main(String[] args) {

int x = 1, y = 2;

char ch = '*';

switch (ch) {

case '+':

System.out.println("x*y=" + (x + y));

break;

case '-':

System.out.println("x-y="+(x-y));

break;

case '*':

System.out.println("x*y="+(x*y));

break;

case '/':

System.out.println("x/y="+(x/y));

break;

default:

System.out.println("不靠譜");

}

}

if 和switch 語句很像具體什麼場景下,應用哪個語句呢?

如果判斷的具體數值不多,而是符號byte,short int char 四種類型.

雖然2個語句都可以使用,建議使用switch語句.因為效率稍高.

其他情況:

對區間判斷,對結果為boolean 型別判斷,使用if if的使用範圍更廣。

if 除了能判斷具體數值還能判斷區間。switch 判斷區間會很費勁的。要寫好多case 對於運算結果是boolean型的 if 能判斷 switch 是不能實現的。例如:根據學生考試成績劃分ABCD   A90-100  B80-89 C70-79 D60-69 E0-59。

 

實際開發怎麼選擇呢?

    如果要對具體數值進行判斷,並且數值不多,那麼 就用switch 來完成。switch的case條件都是編譯期整數常量,編譯器可以做到表格跳轉查詢,查詢速度快。

但是switch 的侷限性比較大必須是4種類型,並且值不多。一般都是使用if。 最後在jdk 7中對switch 進行了增強 還可以判斷字串。5.0 增加了對列舉的判斷。

 

備註:JDK7.0開始可以使用switch可以使用字串型別的資料了.

  1. While迴圈

需求:需要列印一行字串"hello gzitcast",100次

就需要將該語句列印100遍System.out.println("hello gzitcast");

那麼如何解決該問題?

Java提供個一個稱之為迴圈的結構,用來控制一個操作的重複執行。

int count = 0;

while (count < 100) {

System.out.println("hello gzitcast");

count++;

}

System.out.println("over");

變數count初始化值為0,迴圈檢查count<100 是否為true,如果為true執行迴圈體(while後{}之間的語句),輸出"hello gzitcast"語句,然後count自增一,重複迴圈,直到count是100時,也就是count<100為false時,迴圈停止。執行迴圈之後的下一條語句。

Java提供了三種類型的迴圈語句:while迴圈,do-while迴圈和for迴圈。

 

1、while語句格式

while(條件表示式)

{

執行語句;

}

 

 

定義需求: 想要列印5次helloworld

public static void main(String[] args) {

System.out.println("hello world");

System.out.println("hello world");

System.out.println("hello world");

System.out.println("hello world");

System.out.println("hello world");

}

2、

 

public static void main(String[] args) {

int x = 0;

while (x < 5) {

System.out.println("hello java ");

}

}

如果是在dos裡編譯和執行,是不會停止,除非系統宕機。需要ctrl+c來結束。

這就是真迴圈或者死迴圈。因為x<5 永遠為真。

public static void main(String[] args) {

int x = 0;

while (x < 5) {

System.out.println("hello java ");

x++;

}

}

讓x自增,那麼就會有不滿足條件的時候。迴圈就會結束。

練習:想要打印出1-100之間的奇數

public static void main(String[] args) {

int x = 1;

while (x < 100) {

System.out.println(x);

x = x + 2;

}

}

 

    

public static void main(String[] args){

int x=1;

while(x<100){

 

if(x%2!=0){

System.out.print(x);

}

x++;

}

System.out.println();

}

練習2:計算1+2+3+4+5+6+7+8+9 的值

int sum = 0;

int i = 1;

while (i < 10) {

sum = sum + i;

i++;

}

System.out.println(sum);

 

注意:要精確控制迴圈的次數。常犯錯誤是是迴圈多執行一次或者少執行一次。

例如會執行101次,想要執行100次,要麼是count初始值為1,然後count<=100

要麼是count初始值為0,coung<100

int count = 0;

while (count <=100) {

System.out.println("hello gzitcast");

count++;

}

System.out.println("over");

 

猜數字遊戲:

編寫程式隨即生成一個0-100之間的隨機數。程式提示使用者輸入一個數字,不停猜測,直到猜對為止。最後輸出猜測的數字,和猜測的次數。並且如果沒有猜中要提示使用者輸入的值是大了還是小了。

思考:

如何生成1-100之間隨機數?

(int)(Math.random()*100)+1;

如何提示使用者輸入數字,

Scanner  sc=new Scanner(System.in);

int guessNum = sc.nextInt();

需要將隨機數和使用者輸入的數字進行比較。

 

猜一次:

Scanner sc = new Scanner(System.in);

int num = (int)(Math.random()*100)+1;

System.out.println("請輸入0-100之間整數");

int guessNum = sc.nextInt();

if (guessNum == num) {

System.out.println("中啦");

} else if (guessNum < num) {

System.out.println("小啦");

} else {

System.out.println("大了");

}

這個程式只能才一次,如何讓使用者重複輸入直到猜對?

可以使用while迴圈

public static void main(String[] args) {

int num = (int)(Math.random()*100)+1;

Scanner sc = new Scanner(System.in);

while (true) {

System.out.println("請輸入1-100之間整數");

int guessNum = sc.nextInt();

if (guessNum == num) {

System.out.println("中啦");

} else if (guessNum < num) {

System.out.println("小啦");

} else {

System.out.println("大了");

}

}

}

 

該方案發現了問題,雖然實現了讓使用者不停的輸入,但是即使猜中了程式也不會停止。

那麼就需要控制迴圈次數了。也就是while() 括號中的條件表示式。當用戶猜測的數和系統生成的數字不相等時,就需要繼續迴圈。

int num = (int)(Math.random()*100)+1;

Scanner sc = new Scanner(System.in);

 

int guessNum = -1;

while (guessNum != num) {

System.out.println("請輸入1-100之間整數");

guessNum = sc.nextInt();

if (guessNum == num) {

System.out.println("中啦");

} else if (guessNum < num) {

System.out.println("小啦");

} else {

System.out.println("大了");

}

}

 

為什麼將guessNum初始化值為-1?因為如果初始化為0到100之間程式會出錯,因為可能是要猜的數。

1:首先程式生成了一個隨機數

2:使用者輸入一個數字

3:迴圈檢查使用者數字和隨機數是否相同,知道相同位置,迴圈結束

 

  1. do while 語句

do while語句格式:

do

{

執行語句;

}while(條件表示式);

do while特點是條件無論是否滿足,

迴圈體至少被執行一次。

 

 

public static void main(String[] args) {

int x = 0, y = 0;

do {

System.out.printl