1. 程式人生 > 實用技巧 >P1025 [NOIP2001 提高組] 數的劃分

P1025 [NOIP2001 提高組] 數的劃分

Scanner物件

Scanner來自java.util工具包,可以實現人機互動,實現輸入輸出

基本語法:

Scanner scanner = new Scanner(System.in);

Scanner類獲取輸入的字串有next()和nextLine()兩種方法

輸入資料之前要判斷使用者是否有輸入資料,hasNext()與hasNextLine()

【演示】

public class ScannerDemo01 {
    public static void main(String[] args) {
        // 建立一個掃描器物件,用於接收鍵盤資料
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入:");
        if(scanner.hasNext()){
            String str = scanner.next();// 通過str接收輸入的資料
            System.out.println("輸入的內容:"+str);
        }
        scanner.close();// IO流記得要關閉,否則會佔用資源
    }
}
執行結果
    請輸入:
	Hello World!
	輸入的內容:Hello

輸入Hello world!發現只輸出Hello

使用NextLine()方式:

public class ScannerDemo02 {
    public static void main(String[] args) {
        // 建立一個掃描器物件,用於接收鍵盤資料
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入:");
        if(scanner.hasNextLine()){
            String str = scanner.nextLine();// 通過str接收輸入的資料
            System.out.println("輸入的內容:"+str);
        }
        scanner.close();// IO流記得要關閉,否則會佔用資源
    }
}
執行結果
    請輸入:
	Hello World!
	輸入的內容:Hello World!

發現輸入Hello World!可以完整輸出!

小結:

  • next():
    • 一定要讀取到有效的字元後才可以結束輸入
    • 對輸入有效字元之前遇到的空白,next()方法會自動去掉
    • 只有輸入有效字元才將其後面輸入的空白作為分隔符或者結束符
    • next()不能得到帶有空格的字串
  • nextLine():
    • 以Enter為結束符,也就是說nextLine()方法返回的是輸入回車之前的所有字元
    • 可以獲得空白

Scanner物件進階

Scanner物件有細顆粒的方法

【演示】

public class ScannerDemo03 {
    public static void main(String[] args) {
        int i = 0;
        float f = 0.0F;
        Scanner scanner = new Scanner(System.in);
        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();
    }
}

Scanner類有:nextInt(),nextFloat(),nextDouble(),nextChar()……

順序結構

  • Java的基本結構是順序結構,除非特別指明,否則將一句一句按順序執行
  • 順序結構是最簡單的演算法結構
  • 語句與語句之間,框與框之間是按從上到下的順序執行的,它是由若干個依次執行的處理步驟組成的,它是任何一個演算法都離不開的一種基本演算法結構

【演示】

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello1");
        System.out.println("Hello2");
        System.out.println("Hello3");
        System.out.println("Hello4");
    }
}
輸出結果:
Hello1
Hello2
Hello3
Hello4

if選擇結構

  • if單選擇結構
  • if雙選擇結構
  • if多選擇結構
  • 巢狀的if結構

if單選擇結構

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

【演示】

public class IfDemo01 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("請輸入一段字元:");
        String str = input.nextLine();
        // equals:判斷字串是否相等
        if(str.equals("hello")){
            System.out.println("輸入的內容為:hello");
        }else{
            System.out.println("輸入的內容不是hello");
        }
        input.close();
    }
}

if雙選擇結構

有些時候我們需要兩個判斷,這樣就要用到我們的if-else結構

【演示】

public class IfDemo02 {
    public static void main(String[] args) {
        /* 成績大於60及格,否則不及格 */
        Scanner input = new Scanner(System.in);
        System.out.println("請輸入成績:");
        double score = input.nextDouble();
        if(score>=60){
            System.out.println("成績及格:"+score);
        }else{
            System.out.println("成績不及格:"+score);
        }
        input.close();
    }
}

if多選擇結構

我們發現剛才的程式碼並不符合實際,成績應該有多個等級(A,B,C,D,E…)

語法結構:
if(布林表示式1){
    //如果布林表示式1為true時執行該程式碼
}else if(布林表示式2){
    //如果布林表示式2為true時執行該程式碼
}else if(布林表示式3){
    //如果布林表示式3為true時執行該程式碼
}else{
    //如果以上布林表示式都不為true則該程式碼
}

public class IfDemo03 {
    public static void main(String[] args) {
        /* 成績大於60且小於80為及格
           成績大於80且小於90為良好
           成績大於90為優秀
           成績小於60為不及格 */
        Scanner input = new Scanner(System.in);
        System.out.println("請輸入成績:");
        double score = input.nextDouble();
        if(score>=60 && score<80){
            System.out.println("成績及格:"+score);
        }else if(score>=80 && score<90){
            System.out.println("成績良好:"+score);
        }else if(score>=90 && score<=100){
            System.out.println("成績優秀:"+score);
        }else if(score<60 && score>=0){
            System.out.println("成績不及格:"+score);
        }else{
            System.out.println("輸入有誤,成績不合法");
        }
        input.close();
    }
}

巢狀的if結構

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

語法:

if(布林表示式1){
    //如果布林表示式1為true時執行該程式碼
    if(布林表示式2){
        //如果布林表示式2為true時執行該程式碼
    }
}
public class IfDemo04 {
    public static void main(String[] args) {
        /* 判斷一個數是否能被2,3,5整除 */
        Scanner input = new Scanner(System.in);
        System.out.println("請輸入一個整數:");
        int i = input.nextInt();
        if(i%2==0){
            if(i%3==0){
                if(i%5==0){
                    System.out.println("這個數能被2,3,5整除");
                }else{
                    System.out.println("這個數不能被2,3,5整除");
                }
            }else{
                System.out.println("這個數不能被2,3,5整除");
            }
        }else{
            System.out.println("這個數不能被2,3,5整除");
        }
        input.close();
    }
}

switch選擇結構

  • 多選擇結構還有一個實現方式就是switch case語句
  • switch case語句判斷一個變數與一系列中某一個值是否相同,每個值稱為一個分支
  • switch語句中的變數可以是:
    • byte.short.int或者char
    • 從JavaSE7開始switch支援字串String型別
    • 同時case標籤必須為字串常量或者字面量
語法:
switch(expression){
    case value:
        //語句
        break;//可選
    case value:
        //語句
        break;//可選
    //你可以有任意數量的case語句
    default://可選
        //語句
}

【演示】

public class SwitchDemo01 {
    public static void main(String[] args) {
        char grade = 'A';
        switch (grade){
            case 'A':
                System.out.println("優秀");
                break;
            case 'B':
                System.out.println("良好");
                break;
            case 'C':
                System.out.println("及格");
                break;
            default:
                System.out.println("未知等級");
        }
    }
}
結果:
優秀

注意case穿透
若沒有遇到break語句將會一直執行下去,直到遇到break語句結束

public class SwitchDemo02 {
    public static void main(String[] args) {
        char grade = 'A';
        switch (grade){
            case 'A':
                System.out.println("優秀");
            case 'B':
                System.out.println("良好");
            case 'C':
                System.out.println("及格");
            default:
                System.out.println("未知等級");
        }
    }
}
結果:
優秀
良好
及格
未知等級

迴圈結構

while迴圈

while是最基本你的迴圈,它的結構為

while(布林表示式){
    //迴圈內容
}
  • 只要布林表示式為true就會一直迴圈下去
  • 我們大多數情況是會讓迴圈停下來,我們需要一個讓表示式失效的方式來結束迴圈
  • 少部分情況需要迴圈一直執行,比如伺服器監聽等
  • 迴圈條件一直為true會造成死迴圈,會影響程式效能或程式卡死崩潰
  • 思考:計算1+2+3…+100的結果
public class Demo{
    public static void mian(String[] args){
        //輸出1~100
        int i = 0;
        while(i<100){
            i++;
            System.out.println(i);
        }
    }
}

死迴圈演示

public class Demo{
    public static void main(String[] args){
        while(true){//布林表示式永遠成立
            //監聽聊天
            //伺服器監聽
            //...
        }
    }
}

計算1+2+3…+100的結果

public class WhileDemo01 {
    public static void main(String[] args) {
        /* 求1+2+3+……+100的和 */
        int i = 1;
        int sum = 0;
        while(i<=100){
            sum+=i;
            i++;
        }
        System.out.println("sum="+sum);
    }
}

do…while迴圈

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

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

    do{
      //程式碼語句
    }while(布林表示式);
    
  • while和do..while的區別

    • while先判斷後執行,do…while先執行後判斷
    • do…while總是保證迴圈體會被至少執行一次!這是他們的主要區別

【演示】

public class DoWhileDemo01 {
    public static void main(String[] args) {
        /* 求1+2+3+……+100的和 */
        int i = 1;
        int sum = 0;
        do{
            sum+=i;
            i++;
        }while(i<=100);
        System.out.println("sum="+sum);
    }
}

【while與do…while區別】

while先判斷後執行語句,do……while先執行語句後判斷

public class Hello {
    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);
    }
}
輸出結果:
===============
0

for迴圈

  • 雖然所有迴圈結構都可以用while和do…while表示,但Java提供了另一種語句—>for迴圈,使一些迴圈結構變得更加簡單

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

  • for迴圈執行的次數是在執行前就確定了,語法結構如下:

    for(初始化;布林表示式;更新){
      //程式碼語句
    }
    for(;;){//死迴圈
    }
    

【for迴圈結構與while迴圈結構的對比】

public class Hello {
    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+=2) {
            System.out.println(i);
        }
        System.out.println("for迴圈結束");
    }
}

for迴圈結構練習

  1. 計算0到100之間的奇數和偶數的和
  2. 用while或for迴圈輸出1-1000之間能被5整除的數,並且每行輸出3個
  3. 列印九九乘法表
// 練習一:計算0到100之間的奇數和偶數的和
public class ForDemo01 {
    public static void main(String[] args) {
        int odd = 0;// 奇數和
        int even = 0;// 偶數和
        for(int i = 1; i <= 100; i++){
            if(i%2==0){
                even += i;
            }else{
                odd += i;
            }
        }
        System.out.println("奇數和odd="+odd);
        System.out.println("偶數和even="+even);
    }
}
// 練習二:用while或for迴圈輸出1-1000之間能被5整除的數,並且每行輸出3個
public class ForDemo02 {
    public static void main(String[] args) {
        int i = 1;
        int count = 0;
        while(i <= 1000){
            if(i%5 == 0){
                System.out.print(i+" ");// print輸出不會換行
                count++;
                if(count%3 == 0){
                    System.out.println();//換行
                }
            }
            i++;
        }
        System.out.println("\n***************");
        count = 0;
        for(int j = 1; j <= 1000; j++){
            if(j%5 == 0){
                System.out.print(j+" ");
                count++;
                if(count%3 == 0){
                    System.out.println();
                }
            }
        }
    }
}
// 練習三:列印九九乘法口訣表
public class ForDemo03 {
    public static void main(String[] args) {
        for(int i = 1; i <= 9; i++){
            for(int j = 1;j <= i; j++){
                System.out.print(i+"*"+j+"="+i*j+"\t");
            }
            System.out.println();// 換行
        }
    }
}
輸出結果:
1*1=1	
2*1=2	2*2=4	
3*1=3	3*2=6	3*3=9	
4*1=4	4*2=8	4*3=12	4*4=16	
5*1=5	5*2=10	5*3=15	5*4=20	5*5=25	
6*1=6	6*2=12	6*3=18	6*4=24	6*5=30	6*6=36	
7*1=7	7*2=14	7*3=21	7*4=28	7*5=35	7*6=42	7*7=49	
8*1=8	8*2=16	8*3=24	8*4=32	8*5=40	8*6=48	8*7=56	8*8=64	
9*1=9	9*2=18	9*3=27	9*4=36	9*5=45	9*6=54	9*7=63	9*8=72	9*9=81	

增強for迴圈

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

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

    for(宣告語句:表示式){
        //程式碼語句
    }
    
  • 宣告語句:宣告新的區域性變數,該變數的型別必須和陣列元素的型別匹配。其作用域限定在迴圈語句塊,其值與此時的陣列元素相等

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

【演示】

public class ForDemo04 {
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5,};
        for(int element: array){
            System.out.println(element);
        }
    }
}
輸出結果
1
2
3
4
5

break和continue

  • break在任何迴圈語句的主體部分,均可用break控制迴圈的流程。break用於強行退出迴圈,不執行迴圈中剩餘的語句(break語句也在switch語句中使用)
  • continue語句在迴圈體中,用於終止某次迴圈條件,即跳過迴圈體中尚未執行的語句,接著進行下一次是否執行迴圈的判定

【break】

public class BreakDemo01 {
    public static void main(String[] args) {
        int i = 1;
        while(i <= 10){
            System.out.println(i);
            if(i == 5){
                break;
            }
            i++;
        }
        System.out.println("***");
    }
}
輸出結果
1
2
3
4
5
***

【continue】

public class ContinueDemo01 {
    public static void main(String[] args) {
        for(int i = 1; i <= 10; i++){
            if(i == 5){
                continue;
            }
            if(i == 8){
                break;
            }
            System.out.println(i);
        }
    }
}
輸出結果
1
2
3
4
6
7

流程控制練習

列印三角形

public class TriangleDemo01 {
    public static void main(String[] args) {
        for(int i = 1; i <= 5; i++){
            for(int j = 5; j >= i; j--){
                System.out.print(" ");
            }
            for(int j = 1; j <= i*2-1; j++){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
輸出結果
     *
    ***
   *****
  *******
 *********