1. 程式人生 > 實用技巧 >Java流程控制學習筆記

Java流程控制學習筆記

Java 流程控制

使用者互動Scanner

Scanner 物件

  • java.util.Scanner是java5的新特徵,我們可以通過Scanner類來獲取使用者的輸入。

  • 基本語法:

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

    1. next():

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

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

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

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

      package com.ronghui.scanner;

      import java.util.Scanner;

      public class Demo01 {
      public static void main(String[] args) {
      //建立一個掃描器物件,用於接收鍵盤資料
      Scanner scanner = new Scanner(System.in);

      System.out.println("使用next方式接受:");

      //判斷使用者有沒有輸入字串
      if (scanner.hasNext()){
      //使用next方式接受
      String str = scanner.next();
      System.out.println("輸入的內容為:"+str);
      }
      //凡是屬於IO流的類如果不關閉會一直佔用資源,要養成良好的習慣用完就關
      scanner.close();
      }
      }

    2. nextLine():

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

      • 可以獲取空白。

      package com.ronghui.scanner;

      import java.util.Scanner;

      public class Demo02 {
      public static void main(String[] args) {
      //從鍵盤接收資料
      Scanner scanner = new Scanner(System.in);
      System.out.println("使用nextLine方式接受:");
      //判斷是否還有輸入
      if (scanner.hasNextLine()){
      String str= scanner.nextLine();//等待使用者輸入
      System.out.println("輸入的內容為:"+str);
      }
      scanner.close();
      }
      }
      1. 補充說明上面的程式中if可以去掉。

        package com.ronghui.scanner;

        import java.util.Scanner;

        public class Demo03 {
        public static void main(String[] args) {
        //從鍵盤接收資料
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入資料:");

        String str= scanner.nextLine();//等待使用者輸入
        System.out.println("輸入的內容為:"+str);
        scanner.close();
        }
        }
        package com.ronghui.scanner;

        import java.util.Scanner;

        public class Demo04 {
        public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        //從鍵盤接受資料
        int i=0;
        float f=0.0f;
        System.out.println("請輸入整數:");

        //如果。。。那麼。。。
        if (scanner.hasNextInt()){
        i = scanner.nextInt();
        System.out.println("整數資料:"+i);
        }else{
        System.out.println("輸入的不是整數資料");
        }

        System.out.println("請輸入小數:");

        //如果。。。那麼。。。
        if (scanner.hasNextFloat()){
        f = scanner.nextFloat();
        System.out.println("小數資料:"+f);
        }else{
        System.out.println("輸入的不是小數資料");
        }



        scanner.close();
        }
        }
        package com.ronghui.scanner;

        import java.util.Scanner;

        public class Demo05 {
        public static void main(String[] args) {
        //我們可以輸入多個數字,並求其總和與平均數,每輸入一個數字用回車確認,通過輸入非數字來結束輸入並輸出執行結果

        Scanner scanner = new Scanner(System.in);
        //和
        double sum=0;
        //計算輸入多少個數字
        int m =0;

        //通過迴圈判斷是否還有輸入,並在裡面對每一次進行求和和統計
        while(scanner.hasNextDouble());{
        double x = scanner.nextDouble();
        m=m+1;//m++
        sum=sum+x;
        System.out.println("你輸入了第"+m+"個數據,當前結果sum="+sum);
        }
        System.out.println(m +"個數的和為:"+sum);
        System.out.println(m +"個數的平均數為:"+sum/m);


        scanner.close();
        }
        }

順序結構

  • Java的基本結構就是順序結構,除非特別指明,否則就按照順序一句一句的執行

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

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

    package com.ronghui.struct;

    public class Demo01 {
    //順序結構
    public static void main(String[] args) {
    System.out.println("hello1");
    System.out.println("hello2");
    System.out.println("hello3");
    System.out.println("hello4");
    System.out.println("hello5");
    }
    }

選擇結構

  • if單選擇結構

    package com.ronghui.struct;

    import javax.print.DocFlavor;
    import java.util.Scanner;

    public class IfDemo01 {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("請輸入內容:");
    String s=scanner.nextLine();
    //判斷字串是否相等的
    if (s.equals("Hello")){
    System.out.println(s);
    }

    System.out.println("End");

    scanner.close();
    }
    }

  • if雙選擇結構

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

  • if多選擇結構

    package com.ronghui.struct;
    
    import java.util.Scanner;
    
    public class IfDemo03 {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            /**
             * if語句至多有一個else語句,在else if語句之後
             * if語句中可以有若干個 else if語句,必須在else語句之前。
             * 一個else if語句為true,其他的else if和else語句都將跳過執行
             */
            System.out.println("請輸入成績:");
            int score = scanner.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("成績不合法");
            }
            scanner.close();
        }
    }
  • 巢狀的if結構

    意思就是if語句裡面能再次只用if語句。

  • switch多選擇結構

    package com.ronghui.struct;
    
    public class SwitchDemo02 {
        public static void main(String[] args) {
            String name ="歐榮輝";
            //JDK7新特性,表示式結果可以是字串
    //字元的本質還是數字
            //反編譯
    
            switch (name){
                case "餘欣":
                    System.out.println("餘欣");
                    break;
                case"歐榮輝":
                    System.out.println("歐榮輝");
                    break;
                default:
                    System.out.println("弄啥了");
    
            }
        }
    }
    package com.ronghui.struct;
    
    public class SwitchDemo01 {
        public static void main(String[] args) {
            //case穿透  switch 匹配一個具體的值
            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("未知等級");
    
            }
        }
    }

迴圈結構

while迴圈

大多數情況會讓迴圈停下來,需要讓一個表示式失效的方式來結束迴圈。

package com.ronghui.struct;

public class WhileDemo03 {
    public static void main(String[] args) {
        //計算1+2+3+。。+100=?
        int i=0;
        int sum=0;
        while (i<100){
            ++i;
            sum=sum+i;
        }
        System.out.println(sum);

    }
}

避免死迴圈

do。。。while迴圈

package com.ronghui.struct;

public class DoWhileDemo01 {
    public static void main(String[] args) {
        int i=0;
        int sum=0;
        do{
          sum=sum+i;
          i++;

        }while(i<=100);
        System.out.println(sum);
    }
}
package com.ronghui.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迴圈

for迴圈,使一些迴圈結構變得更簡單。

for迴圈是知識迭代的一種通用結構,是最有效、最靈活的迴圈結構

package com.ronghui.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,迴圈終止,開始執行迴圈體後邊的語句。

執行一次迴圈後,更新迴圈控制變數(迭代因子控制變數的增減)。

再次檢測布林值表示式。迴圈上面的過程。

練習1:

package com.ronghui.struct;

public class ForDemo02 {
    public static void main(String[] args) {
        //計算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:

package com.ronghui.struct;

public class ForDemo03 {
    public static void main(String[] args) {
        //用while或這for迴圈輸出1-1000之間能被5整除的數,並且每行輸出3個
        for (int i = 0; i <= 1000; i++) {
            if (i%5==0){
                System.out.print(i+"\t");
            }
            if(i%15==0){
                System.out.println();
            }
            //println 輸出完會換行
            //print輸出完不會換行
        }
    }
}

練習3:列印99乘法表

package com.ronghui.struct;

public class ForDemo04 {
    public static void main(String[] args) {
        for (int j = 1; j <= 9; j++) {
            for (int i = 1; i <= j; i++) {
                System.out.print(j+"*"+i+"="+(j*i)+"\t");
            }
            System.out.println();
        }
        //1.首先列印第一列,輸出1*1~1*9
        //2.把固定的1再用迴圈包起來,把1變成變數
        //3.使用i<=j來去掉重複項
        //4.調整樣式
    }
}

for 。。。增強:

package com.ronghui.struct;

public class ForDemo05 {
    public static void main(String[] args) {
        int [] numbers={10,20,30,40,50};//定義一個數組

        for (int i=0;i<5;i++){
            System.out.println(numbers[i]);
        }
        System.out.println("==============");
        //遍歷陣列的元素
        for (int x:numbers){
            System.out.println(x);
        }
    }
}

break&continue

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

    package com.ronghui.struct;
    
    public class BreakDemo01 {
        public static void main(String[] args) {
            int i=0; 
            while (i<100){
                i++;
                System.out.println(i);
                if (i==30){
                    break;
                }
            }
        }
    }

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

    package com.ronghui.struct;
    
    public class ContinueDemo01 {
        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");
            }
        }
    }

練習

package com.ronghui.struct;

import java.awt.*;

public class TestDemo01 {
    public static void main(String[] args) {
        //列印三角形 5行
        for (int i = 1; i <= 5; i++) {
            for (int j=5;j>=i;j--){
                System.out.print(" ");
            }
            for (int j=1;j<=i;j++){
                System.out.print("*");
            }
            for (int j=1;j<i;j++){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}