1. 程式人生 > 實用技巧 >java流程控制

java流程控制

java流程控制

1.使用者互動Scanner(Scanner物件)

  • 基本語法中沒有實現程式和人的互動,但是java給我們提供了這樣一個工具類,我們可以獲取使用者的輸入。java.util.Scanner是java5的新特徵,我們可以通過Scanner類來獲取使用者的輸入

  • 基本語法:

  • 通過Scanner類的next()與nextLine()方法獲取輸入的字串,在讀取前我們一般需要使用hasNext()與hasNextLine()判斷是否還有輸入的資料。

Scanner物件

  • next():

    • 一定要讀取到有效字元後才可以結束輸入。

    • 對輸入有效字元之前遇到的空白,next() 方法會自動將其去掉

    • 只有輸入有效字元後才將其後面輸入的空白作為分隔符或者結束符。

    • next()不能得到帶有空格的字串

  • nextLine():

    • 以Enter為結束符,也就是說nextLine()方法返回的是輸入回車之前的所有字元。

    • 可以獲取空白。

       package com.langlang.base;
       ​
       import java.util.Scanner;
       ​
       public class ScannerDemo {
       ​
           public static void main(String[] args) {
       ​
               //建立一個掃描器物件,用於接收鍵盤資料
               Scanner scanner = new
      Scanner(System.in); ​ System.out.println("使用next方法接收:"); ​ //判斷使用者有沒有錄入字串 if (scanner.hasNext()){ String str = scanner.next(); System.out.println("輸入的字串為:"+str); } ​ System.out.println("使用nextLine方法接收:"); String str1 = scanner.nextLine(); System.out.println(
      "接收的內容為(可接受包含空格的字串):"+str1); ​ //從鍵盤接收資料 int i = 0; float f = 0.0f; System.out.println("請輸入整數:"); //i = sc.nextInt(); //如果。。。那麼 if (scanner.hasNextInt()){ i = scanner.nextInt(); System.out.println("整數資料:"+i); }else{ System.out.println("輸入的不是整數資料"); ​ } ​ ​ System.out.println("請輸入小數:"); //i = sc.nextFloat(); //如果。。。那麼 if (scanner.hasNextFloat()){ f = scanner.nextFloat(); System.out.println("小數資料:"+f); }else{ System.out.println("輸入的不是小數資料1"); ​ } ​ //凡是屬於IO流的類如果不關閉會一直佔用資源,要養成好習慣用完關掉 scanner.close(); ​ } ​ }
    • 進階

      
      
      
      package com.langlang.scanner;
       ​
       import java.util.Scanner;
       ​
       public class Demo02 {
           public static void main(String[] args) {
       ​
               //我們可以輸入多個數字,並求其總和與平均數,每輸入一個數字用回車確認,通過輸入非數字來結束輸入並輸出執行結果:
               Scanner scanner = new Scanner(System.in);
       ​
               //
               double sum = 0;
               //計算輸入了多少個數字
               int m = 0;
       ​
               //通過迴圈判斷是否還有輸入,並在裡面對每一次進行求和和統計
               System.out.println("輸入資料:");
               while(scanner.hasNextDouble()){
                   double x = scanner.nextDouble();
       ​
                   m = m+1;//m++
                   sum = sum + x;
               }
               System.out.println(m+"個數的和為"+sum);
               System.out.println(m+"個數的平均值是"+(sum/m));
           }
       }


2.順序結構

  • java的基礎結構就是順序結構,除非特別說明,否則就按照順序一句一句執行。

  • 順序結構是最簡單的演算法結構。

  • 語句與語句之間,框與框之間是按從上到下的順序進行的,它是由若干個依次執行的處理步驟組成的,它是任何一個演算法都離不開的一種基本演算法結構。

3.選擇結構

  • if單選結構

    • 去判斷一個東西是否可行,然後我們才去執行,這樣的過程在程式中用if語句來表示

    • 語法:

      
      
      
      package com.langlang.struct;
       ​
       import java.util.Scanner;
       ​
       public class ifDemo01 {
           public static void main(String[] args) {
       ​
               Scanner sc = new Scanner(System.in);
       ​
               System.out.println("請輸入內容:");
               String s = sc.nextLine();
       ​
               //equals:判斷字串是否相等
               if (s.equals("hello")){
                   System.out.println("輸入正確!");
               }
       ​
       ​
               sc.close();
       ​
           }
       }


  • if雙選結構

    • 一個企業要收購器械,成功了,給人支付200萬元;失敗了,合作破裂。如此,用一個if就無法搞定,我們需要兩個判斷,也就是if-else結構。

    • 語法:

       package com.langlang.struct;
       ​
       import java.util.Scanner;
       ​
       public class ifDemo02 {
           public static void main(String[] args) {
               Scanner sc = new Scanner(System.in);
       ​
               //if-else結構
               //考試分數大於60是及格,小於60是不及格
               System.out.println("請輸入成績:");
               int score = sc.nextInt();
       ​
               if (score>60){
                   System.out.println("及格!");
               }else{
                   System.out.println("不及格!");
               }
       ​
       ​
               sc.close();
           }
       }


  • if多選結構

    • 不符合if-else結構,存在區間多級判斷的。在生活中我們很多時候的選擇也不僅僅是隻有兩個,所以我們需要一個多選擇結構來處理這類問題。

    • 語法:

      
      
      
      package com.langlang.struct;
       ​
       import java.util.Scanner;
       ​
       public class ifDemo02 {
           public static void main(String[] args) {
               Scanner sc = new Scanner(System.in);
       ​
       ​
               /*
               if語句至多有一個else語句,else語句在所有的else if 語句之後。
               if語句可以有若干個 else if 語句,它們必須在else 語句之前。
               一旦其中一個 else if 語句檢測為 true , 其他的 else if 以及 else  語句都將跳過執行。
               */
       ​
               System.out.println("請輸入成績:");
               int score = sc.nextInt();
       ​
               if (score==100){
                   System.out.println("恭喜滿分!");
               }else if(score<100 && score>=90){
                   System.out.println("A級");
               }else if(score<90 && score>=80){
                   System.out.println("B級");
               }else if(score<80 && score>=70){
                   System.out.println("C級");
               }else if(score<70 && score>=60){
                   System.out.println("D級");
               }else if(score<60 && score>=0){
                   System.out.println("不及格!");
               }else{
                   System.out.println("成績不合法!");
               }
       ​
       ​
               sc.close();
           }
       }
       ​

  • 巢狀的if結構

    • 使用巢狀的if...else 語句是合法的。也就是說你可以在另一個if或者else if語句中使用 if 或者 else if語句。

    • 語法;

       package com.langlang.struct;
       ​
       import java.util.Scanner;
       ​
       public class ifDemo03 {
           public static void main(String[] args) {
               Scanner sc = new Scanner(System.in);
       ​
               //輸入一個數,判斷其是否是整數,輸出是整數,輸出能被三整除的整數
               System.out.println("請輸入整數:");
               int i = sc.nextInt();
               if (i%2==0){
                   System.out.println("輸入資料是整數!");
                   if (i%3==0){
                       System.out.println("該數還是3的倍數");
                   }
               }
               
               sc.close();
           }
       }
       ​

  • switch多選擇結構

    • 多選擇結構還有一個實現方式就是switch case 語句。

    • switch case 語句判斷一個變數與一個系列值中某個值是否相等,每個值稱為一個分支。

    • switch語句中的變數型別可以是:

      • byte、short、int 或者 char 。

      • 從 java SE 7開始

      • switch支援字串String型別了

      • 同時case標籤必須為字串常量或字面量。

        
        
        
        package com.langlang.struct;
         ​
         public class switchDemo01 {
             public static void main(String[] args) {
         ​
                 char grade = 'C';
         ​
                 switch (grade){
                     case 'A':
                         System.out.println("優秀");
                         break;
                     case 'B':
                         System.out.println("良好");
                         break;
                     case 'C':
                         System.out.println("及格");
                         break;
                     case 'D':
                         System.out.println("再接再厲");
                         break;
                     case 'E':
                         System.out.println("涼涼");
                         break;
                     default:
                         System.out.println("未知");
                 }
         ​
         ​
                 //JDK7d的新特性,表示式結果可以是字串!!!
                 //字元的本質還是數字
        //反編譯   java------class(位元組碼檔案)----------反編譯(IDEA)
                 String s = "浪浪";
         ​
                 switch (s){
                     case "浪浪":
                         System.out.println("輸出的是浪浪呀!");
                         break;
                     case "學醫":
                         System.out.println("輸出學醫!");
                         break;
                 }
         ​
         ​
             }
         }
         ​

4.迴圈結構

  • while迴圈

    • while是最基本的迴圈,它的結構是:

    • 只要布林表示式為true,迴圈就會一直執行下去。

    • 我們大多數情況是會讓迴圈停止下來的,我們需要以一個表示式失效的方法來結束迴圈。

    • 少部分情況需要迴圈一直執行,比如伺服器的請求響應監聽等。

    • 迴圈條件一直未true就會造成無限迴圈【死迴圈】,我們正常的業務程式設計中應該儘量避免死迴圈。會影響程式效能或者造成程式卡死崩潰!

      
      
      
      package com.langlang.struct;
       ​
       public class WhileDemo01 {
           public static void main(String[] args) {
       ​
               //輸出1~100
      int i =0;
       ​
               while(i<100){
                   i++;
                   System.out.println(i);
               }
       ​
               //計算1+2+3+...+100=?
               int sum = 0;
               int s = 0;
       ​
               while (s<=100){
                   sum+=s;
                   s++;
               }
               System.out.println(sum);
       ​
       ​
           }
       }
       ​

  • do.....while迴圈

    • 對於while語句而言,如果不滿足條件,則不能進入迴圈。但有時候我們需要即使不滿足條件,也至少執行一次。

    • do....while 迴圈和while迴圈相似,不同的是,do...while迴圈至少會執行一次。

       package com.langlang.struct;
       ​
       public class dowhileDemo01 {
           public static void main(String[] args) {
       ​
               int i = 0;
               int sum = 0;
               do {
                   sum += i;
                   i++;
               }while (i<=100);
       ​
               System.out.println(sum);
       ​
           }
       }
       ​

    • while和do...while的區別:

      • while先判斷後執行。do...while是先執行後判斷!

      • do...while總是保證迴圈體會被至少執行一次!這是他們的主要差別。

         package com.langlang.struct;
         ​
         public class dowhileDemo02 {
             public static void main(String[] args) {
         ​
                 int a = 0;
                 while (a<0){
                     System.out.println(a);
                     a++;
                 }
                 System.out.println("=======================");
                 do {
                     System.out.println(a);
                     a++;
                 }while (a<0);
         ​
             }
         }
         ​

  • for迴圈

    • 雖然所有的迴圈結構都可以用while或者do...while表示,但java提供了另一種語句--------for迴圈,使一些迴圈結構變的更加簡單。

    • for迴圈語句是支援迭代的一種通用結構,是最有效、最靈活的迴圈結構。

    • for迴圈執行的次數是在執行前就確定的。語法格式如下:

       package com.langlang.struct;
       ​
       public class forDemo01 {
           public static void main(String[] args) {
       ​
               int a = 1;//初始化條件
      while (a<=100){//條件判斷
       ​
                   System.out.println(a);//迴圈體
                   a+=2;//迭代
               }
               System.out.println("while迴圈結束!");
       ​
               //初始化//條件判斷//迭代
               for (int i = 1;i<=100;i++){
                   System.out.println(i);
               }
               System.out.println("for迴圈結束!");
       ​
       ​
               /*
               關於for迴圈有一下幾點說明:
       ​
               最先執行初始化步驟。可以宣告一種型別,但可初始化一個或多個迴圈控制變數,也可以是空語句。
               然後,檢測布林表示式的值。如果為true,迴圈體被執行。如果為false,迴圈終止,開始執行迴圈體後面的語句。
               執行一次迴圈後,更新迴圈控制變數(迭代因子控制迴圈變數的增減)。
               再次檢測布林表示式。迴圈執行上面的過程。
               */
               
               //死迴圈
               for (; ; ){
                   
               }
       ​
       ​
           }
       }
       ​
       ​

    • 練習1:計算0到100之間的奇數和偶數的和

       package com.langlang.struct;
       ​
       public class ForDemo001 {
           public static void main(String[] args) {
       ​
               //練習1:計算0到100之間的奇數和偶數的和
               int oddSum = 0;//奇數
               int evenSum =0;//偶數
      for (int i=0;i<=100;i++){
                   if (i%2!=0){
                       oddSum+=i;
                   }else{
                       evenSum+=i;
                   }
               }
               System.out.println("奇數的和"+oddSum);
               System.out.println("偶數的和"+evenSum);
       ​
           }
       }
       ​

    • 練習2:用while或for迴圈輸出1-1000之間能被5整除的數,並且每行輸出3個

      
      
      
      package com.langlang.struct;
       ​
       public class ForDemo002 {
           public static void main(String[] args) {
       ​
               //練習2:用while或for迴圈輸出1-1000之間能被5整除的數,並且每行輸出3個
      for (int i=0;i<=1000;i++){
                   if (i%5==0){
                       System.out.print(i+"\t");
                   }
                   if (i%(5*3)==0){
                       System.out.println();
                   }
               }
       ​
           }
       }
       ​

    • 練習3:列印九九乘法表

      
      
      
      package com.langlang.struct;
       ​
       public class ForDemo003 {
           public static void main(String[] args) {
       ​
               //練習3:列印九九乘法表
      for (int i = 1;i<=9;i++){
                   for (int y = 1;y<=i;y++){
                       System.out.print(i+"*"+y+"="+(i*y)+"\t");
                   }
                   System.out.println();
               }
       ​
           }
       }
       ​

  • 在java5中引入了一種主要用於陣列的增強型for迴圈

    • java增強for迴圈語法格式如下:

    • 宣告語句:宣告新的區域性變數,該變數的型別必須和陣列元素的型別匹配。其作用域限定在迴圈語句塊,其值與此時陣列元素的值相等。

    • 表示式:表示式是要訪問的陣列名,或者是返回值為陣列的方法。

      
      
      
      package com.langlang.struct;
       ​
       public class ForDemo05 {
           public static void main(String[] args) {
       ​
               int[] numbers = {10,20,50,40,60};//定義了一個數組
      for (int i = 0;i<5;i++){
                   System.out.println(numbers[i]);
               }
               System.out.println("===============================");
       ​
               //遍歷陣列的元素
               for (int i:numbers){
                   System.out.println(i);
               }
       ​
           }
       }
       ​

5.break & continue

  • break在任何迴圈語句的主體部分,均可用break控制迴圈的流程。break用於強行退出迴圈,不執行迴圈中剩餘的語句。(break語句也在switch語句中使用)

    
    
    
    package com.langlang.struct;
     ​
     public class BreakDemo {
         public static void main(String[] args) {
     ​
             //用法1:在迴圈中,強制停止迴圈
             int i = 0;
             while (i<100){
                 i++;
                 System.out.println(i);
                 if (i==30){
                     break;//只中斷迴圈,迴圈外面的語句正常執行
                 }
             }
             System.out.println("123");
     ​
             //用法2:在switch中使用
             char grade = 'C';
     ​
             switch (grade){
                 case 'A':
                     System.out.println("優秀");
                     break;//執行後退出switch語句
                 case 'B':
                     System.out.println("良好");
                     break;
                 case 'C':
                     System.out.println("及格");
                     break;
                 case 'D':
                     System.out.println("再接再厲");
                     break;
                 case 'E':
                     System.out.println("涼涼");
                     break;
                 default:
                     System.out.println("未知");
             }
     ​
     ​
         }
     }
     ​

  • continue語句用在迴圈語句體重,用於終止某次迴圈過程,即跳過迴圈體中尚未執行的語句,接著進行下一次是否執行迴圈的判定。

     package com.langlang.struct;
     ​
     public class ContinueDemo {
         public static void main(String[] args) {
     ​
             int i = 0;
             while (i<100){
                 i++;
                 if (i%10==0){
                     System.out.println("");
                     continue;
                 }
                 System.out.print(i+"\t");
             }
     ​
             //break在任何迴圈語句的主體部分,均可用break控制迴圈的流程。
             // break用於強行退出迴圈,不執行迴圈中剩餘的語句。(break語句也在switch語句中使用)
    //continue語句用在迴圈語句體中,用於終止某次迴圈過程,即跳過迴圈體中尚未執行的語句,接著進行下一次是否執行迴圈的判定。
     ​
         }
     }
     ​

  • 關於goto關鍵字

    • goto關鍵字很早就在程式設計語言中出現。儘管goto仍是java的一個保留字,但並未在語言中得到正式使用;java沒有goto。然而,在break和continue這兩個關鍵字的身上,我們仍然能看出一些goto的影子---帶標籤的break和continue。

    • “標籤”是指後面跟一個冒號的識別符號,例如:label:

    • 對java來說唯一用到標籤的地方是在迴圈語句之前。而在迴圈之前設定標籤的唯一理由是:我們希望在其中巢狀另一個迴圈,由於break和continue關鍵字通常只中斷當前迴圈,但若隨同標籤使用,它們就會中斷到存在標籤的地方。

瞭解



package com.langlang.struct;
 ​
 public class LableDemo {
     public static void main(String[] args) {
 ​
         //列印101-150之間所有的質數
         //質數是指在大於1的自然數中,除了1和它本身以外不再有其他因數的自然數。
int count = 0;
 ​
         outer:for (int i =101;i<150;i++){
             for (int j=2;j<i/2;j++){
                 if (i%j == 0){
                     continue outer;
                 }
             }
             System.out.println(i+"");
         }
 ​
     }
 }
 ​

6.練習

輸出三角形

 package com.langlang.struct;
 ​
 public class TestDemo {
     public static void main(String[] args) {
 ​
         //列印三角形 5行
for (int i = 1; i <= 5; i++) {
             for (int j = 5; j >= i; j--) {
                 System.out.print("\t");
             }
             for (int a = 1;a<=i;a++){
                 System.out.print("#"+"\t");
             }
             for (int b=1;b<i;b++){
                 System.out.print("#"+"\t");
             }
             System.out.println();
         }
 ​
     }
 }
 ​
 ​