03-選擇

03-選擇

  • 3.1 引言

    • 程序可以基于條件決定執(zhí)行哪些語句。
  • 3.2 boolean數(shù)據(jù)類型

    • boolean數(shù)據(jù)類型聲明一個具有true或者flase的變量。
    • 相等的關(guān)系操作符是兩個等號(==),而不是一個等號(=),比較的結(jié)果是一個布爾值:true或flase。true和flase都是字面值,他們被當做保留字一樣,不能用作程序的標識符.
    操作符 名稱
    < 小于
    <= 小于等于
    > 大于
    >= 大于等于
    == 等于
    != 不等于
  • 3.3 if語句
    • if語句是一個構(gòu)造,允許程序確定執(zhí)行的可選路徑。
    • Java中有幾種類型的選擇語句:單分支if語句、雙分支if-else語句、嵌套if語句、多分支if-else語句、switch語句和條件操作符。
    • 單分支if語句是指當且僅當條件為true是執(zhí)行的一個動作。單分支if語句的語法是:
    ```java
    if(布爾表達式){
    語句(組);
    }
    ```
    ![在這里插入圖片描述](https://upload-images.jianshu.io/upload_images/24494503-5ca330b35cdc6ff5?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 示例:
    - 提示用戶輸入一個整數(shù)。如果該數(shù)字是5的倍數(shù),打印HiFive。如果該數(shù)字能被2整除,打印HiEven。
    

        ```java
        package chapter03;
        
        import java.util.Scanner;
        
        public class SimpleIfDemo {
            public static void main(String[] args){
                Scanner input = new Scanner(System.in);
                System.out.print("Enter an integer: ");
                int number = input.nextInt();
        
                if (number % 5 ==0)
                    System.out.println("HiFive");
        
                if (number % 2 ==0)
                    System.out.println("HiEven");
            }
        }
        
        ```
  • 3.4 雙分支 if-else 語句
    • if-else語句根據(jù)條件是真或者是假,決定執(zhí)行的路徑。下面是雙分支if-else語句的語法:
    ```java
    if(布爾表達式){
    布爾表達式為真時執(zhí)行的語句(組);
    }
    else{
    布爾表達式為假時執(zhí)行的語句(組);
    }
    ```
    ![在這里插入圖片描述](https://upload-images.jianshu.io/upload_images/24494503-4d9492d0d083e87b?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  • 3.5 嵌套的if語句和多分支if-else語句
    • if語句可以在另外一個if語句中,形成嵌套的if語句。
    ```java
    if (i > k){
                if (j > k)
                    System.out.println("i and j are greater than k");
            }
            else
                System.out.println("i is less than or equal to k");
    ```
  • 3.6 常見錯誤和陷進
    • 常見錯誤1:忘記必要的括號
    • 常見錯誤2:錯誤地在if行出現(xiàn)分號
    • 常見錯誤3:對布爾值的冗余測試
    • 常見錯誤4:懸空else出現(xiàn)的歧義(每一組if-else都要進行相應(yīng)的縮進進行對齊,避免造成if-else不匹配的現(xiàn)象)
    • 常見錯誤5:兩個浮點數(shù)值的相等測試
    • 常見陷阱1:簡化布爾變量賦值
    ```java
    if (number % 2 == 0)
                even = true;
            else
                even = false;
            //上面的代碼就等價于下面的代碼,但是 下面的代碼形式會更加的好
            boolean even
                    = number % 2 ==0;
    ```
- 常見陷阱2:避免不同情形中的重復代碼

    
    ```java
    package chapter01;
    
    public class Try {
        public static void main(String[] args){
            int tuition;
            boolean inState = true;
            if (inState){
                tuition = 5000;
                System.out.println("The tuition is " + tuition);
            }
            else {
                tuition = 15000;
                System.out.println("The tuition is " + tuition);
            }
            //上面的代碼等價于下面的代碼,但是下面的代碼的形式會更加的好,顯得更加的簡捷
            
            if (inState){
                tuition = 5000;
            }
            else {
                tuition = 15000;
            }
            System.out.println("The tuition is " + tuition);
        }
    }
    
    ```
  • 3.7 產(chǎn)生隨機數(shù)
    • 使用Math.random()來獲得一個0.0到1.0之間的隨機double值,不包括1.0
    • 示例:假設(shè)你想開發(fā)一個讓一年級學生練習減法的程序。程序隨機生成兩個一位整數(shù):number1,number2,且滿足number1>=number2。程序向?qū)W生顯示問題,例如,“What is 9-2?”。當學生輸入答案之后,程序會顯示一個消息表明改答案是否正確。
    ```java
    package chapter03;
    
    import java.util.Scanner;
    
    public class SubtractionQuiz {
        public static void main(String[] args){
            int number1 = (int)(Math.random() * 10);
            int number2 = (int)(Math.random() * 10);
            if (number1 < number2){
                int temp = number1;
                number1 = number2;
                number2 = temp;
            }
    
            System.out.print("What is " + number1 + "-" + number2 + "?");
            Scanner input = new Scanner(System.in);
            int answer = input.nextInt();
            
            if (number1 - number2 == answer)
                System.out.println("You are correct!");
            else {
                System.out.println("Your answer is wrong.");
                System.out.println(number1 + "-" + number2 + " should be " + (number1 - number2));
            }
        }
    }
    
    ```
  • 3.8 示例學習:計算身體質(zhì)量指數(shù)

    package chapter03;
    
    import java.util.Scanner;
    
    public class ComputeAndInterpretBMI {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
    
            System.out.print("Enter weight in pounds: ");
            double weight = input.nextDouble();
    
            System.out.print("Enter height in inches: ");
            double height = input.nextDouble();
    
            final double KILOGRAMS_PER_POUND = 0.45359237;
            final double METERS_PER_INCH = 0.0254;
    
            double weightInKilograms = weight * KILOGRAMS_PER_POUND;
            double heightInMeters = height * METERS_PER_INCH;
            double bmi = weightInKilograms / (heightInMeters * heightInMeters);
    
            System.out.println("BMI is " + bmi);
            if (bmi < 18.5)
                System.out.print("Underweight");
            else if (bmi < 25)
                System.out.println("Normal");
            else if (bmi < 30)
                System.out.println("Overweight");
            else
                System.out.println("Obese");
        }
    }
    
    
  • 3.9 示例學習:計算稅率

    package chapter03;
    
    import java.util.Scanner;
    
    public class ComputeTax {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
    
            System.out.print("(0-single filer,1-married jointly or " + "qualifying window(er),2-married separately,3-head of " + "household) Enter the filing status: ");
    
            int status = input.nextInt();
    
            System.out.print("Enter the taxable income: ");
            double income = input.nextDouble();
    
            double tax = 0;
    
            if (status == 0){
                if (income <= 8350)
                    tax = income * 0.10;
                else if (income <= 33950)
                    tax = 8350 * 0.10 + (income - 8350) * 0.15;
                else if (income <= 82250)
                    tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25;
                else if (income <= 171550)
                    tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (income - 82250) * 0.28;
                else if (income <= 372950)
                    tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (income - 171550) * 0.22;
                else 
                    tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (372950 - 171550) * 0.22 + (income - 372950) * 0.35;
            }
            else if (status == 1){
                //
            }
            else if (status == 2){
                //
            }
            else if (status == 3){
                //
            }
            else {
                System.out.println("Error:invalid status");
                System.exit(1);
            }
            System.out.println("Tax is " + (int)(tax * 100) / 100.0);
        }
    }
    
    
  • 3.10 邏輯操作符

    • 邏輯操作符!、&&、||和^可以用于產(chǎn)生復合布爾表達式。
    操作符 名稱 說明
    ! 邏輯非
    && 邏輯與
    | 邏輯或
    ^ 異或 邏輯異或
```java
package chapter03;

import java.util.Scanner;

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

        System.out.print("Enter an integer: ");
        int number = input.nextInt();

        if (number % 2 == 0 && number % 3 == 0)
            System.out.println(number + "is divisible by 2 and 3.");
        if (number % 2 == 0 || number % 3 == 0)
            System.out.println(number + "is divisible by 2 or 3.");
        if (number % 2 == 0 ^ number % 3 == 0)
            System.out.println(number + "is divisible by 2 or 3,but not both.");
    }
}

```
- 從數(shù)學的角度看,1<=2<=3是正確的,但是在Java中必須將兩個部分分開的,1<=2&&2<=3。
  • 3.11 示例學習:判定閏年

    package chapter03;
    
    import java.util.Scanner;
    
    public class LeapYear {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            System.out.print("Enter a year: ");
            int year = input.nextInt();
    
            boolean isLeapYear = ((year % 4 ==0 && year % 100 == 0) || (year % 400 == 0));
    
            System.out.println(year + " is a leap year? " + isLeapYear);
        }
    }
    
    
  • 3.12 示例學習:彩票

    package chapter03;
    
    import java.util.Scanner;
    
    public class Lottery {
        public static void main(String[] args){
            int lottery = (int)(Math.random() * 100);
    
            Scanner input = new Scanner(System.in);
            System.out.print("Enter your lottery pick (two digits): ");
            int guess = input.nextInt();
    
            int lotteryDigit1 = lottery / 10;
            int lotteryDigit2 = lottery % 10;
    
            int guessDigit1 = guess / 10;
            int guessDigit2 = guess % 10;
            System.out.println("The lottery number is " + lottery);
    
            if (guess == lottery)
                System.out.println("Exact match: you win $10,000");
            else if (guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2)
                System.out.println("Match all digits: you win $3,000");
            else if (guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit2 == lotteryDigit1 || guessDigit2 == lotteryDigit2)
                System.out.println("Match one digit: you win $1,000");
            else
                System.out.println("Sorry, no match");
        }
    }
    
    
  • 3.13 switch語句

    • switch語句基于變量或者表達式的值來執(zhí)行語句,下面是switch語句的完整語句。
    ```java
    switch(switch表達式){
        case 值1:語句(組)1;
                break;
        case 值2:語句(組)2;
                break;
        ...
        case 值N:語句(組)N;
                break;
        default:默認情況下執(zhí)行的語句(組)
    }
    ```
- switch語句遵從下述規(guī)則:
    - 1、switch表達式必須是能計算出一個char、byte、short、int或者String型值,并且需用括號括主。
    - 2、value1,value2,...,valueN必須與swtch表達式具有相同的數(shù)據(jù)類型。注意:value1,value2,...,valueN都是常量表達式,也就是說這里的表達式是不能包含變量的,例如,不允許出現(xiàn)1+x。
    - 3、當switch表達式的值與case語句的值相匹配時,執(zhí)行從case開始的語句,直到遇到一個break語句或到達該switch語句的結(jié)束。
    - 4、默認情況下(default)是可選的,當沒有一個給出的case與switch表達式匹配時,則執(zhí)行該操作。
    - 5、關(guān)鍵字break是可選的。break語句會立即終止switch語句。
    

        ```java
        package chapter03;
        
        import java.util.Scanner;
        
        public class ChineseZodiac {
            public static void main(String[] args){
                Scanner input = new Scanner(System.in);
                
                System.out.print("Enter a year: ");
                int year = input.nextInt();
                
                switch (year % 12){
                    case 0:System.out.println("monkey");break;
                    case 1:System.out.println("rooster");break;
                    case 2:System.out.println("dog");break;
                    case 3:System.out.println("pig");break;
                    case 4:System.out.println("rat");break;
                    case 5:System.out.println("ox");break;
                    case 6:System.out.println("tiger");break;
                    case 7:System.out.println("rabbit");break;
                    case 8:System.out.println("dragon");break;
                    case 9:System.out.println("snake");break;
                    case 10:System.out.println("horse");break;
                    case 11:System.out.println("sheep");break;
                }
            }
        }
        
        ```
- 不要忘記在需要的時候使用break語句。一旦匹配其中一個case,就從匹配的case處開始執(zhí)行, 遇到break語句或者到達switch語句的結(jié)束。這種現(xiàn)象稱為落空行為。
  • 3.14 條件操作
    • 符號?和:一起出現(xiàn),稱為條件操作符(也稱為三元操作符,是Java中唯一的一個三元操作符)該語法如下:
    ```java
    boolean-expression?expression1:expression2
    ```


    ```java
    if(x>0)
        y=1;
    else
        y=-1;
    ```
    和下面的三元操作符是等價的:
    

    ```java
    y=(x>0)?1:-1;
    ```
  • 3.15 操作符的優(yōu)先級和結(jié)合規(guī)則


    在這里插入圖片描述
  • 3.16 調(diào)試

    • 調(diào)試是在程序中找到和修改錯誤的過程。
    • 1、一次執(zhí)行一條語句
    • 2、跟蹤進入或者一步運行一個方法
    • 3、設(shè)置斷點
    • 4、顯示變量
    • 5、顯示調(diào)用堆棧
    • 6、修改變量
  • 編程小習題

    • 1、
      在這里插入圖片描述
      package chapter03;
      
      import java.util.Scanner;
      
      public class Code_01 {
          public static void main(String[] args){
              Scanner input = new Scanner(System.in);
              System.out.print("Enter a,b,c: ");
              double a = input.nextDouble();
              double b = input.nextDouble();
              double c = input.nextDouble();
              double discriminant = b * b - 4 * a * c;
              if (discriminant > 0){
                  double answer1 = (-b + Math.pow(discriminant,0.5)) / (2 * a);
                  double answer2 = (-b - Math.pow(discriminant,0.5)) / (2 * a);
                  System.out.println("The equation has two roots " + answer1 + " and " + answer2);
              }
              else if (discriminant == 0){
                  double answer1 = (-b + Math.pow(discriminant,0.5)) / (2 * a);
                  System.out.println("The eqution has one root " + answer1);
              }
              else
                  System.out.println("The eqution has no real roots");
          }
      }
      
      
    • 2、
      在這里插入圖片描述
    ```java
    package chapter03;
    
    import java.util.Scanner;
    
    public class Code_03 {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            System.out.print("Enter a,b,c,d,e,f: ");
            double a = input.nextDouble();
            double b = input.nextDouble();
            double c = input.nextDouble();
            double d = input.nextDouble();
            double e = input.nextDouble();
            double f = input.nextDouble();
            double medius = a * d - b * c;
            if (medius == 0){
                System.out.println("The eqution has no solution");
            }
            else{
                double x = (e * d - b * f) / medius;
                double y = (a * f - e * c) / medius;
                System.out.println("x is " + x + " and y is " + y);
            }
        }
    }
    
    ```
        - 3、![在這里插入圖片描述](https://upload-images.jianshu.io/upload_images/24494503-775fd080b757aa68?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    ```java
    package chapter03;
    
    import java.util.Random;
    
    public class Code_04 {
        public static void main(String[] args){
            Random r = new Random();
            int month = r.nextInt(12) + 1;
            switch (month){
                case 1:System.out.println("January");break;
                case 2:System.out.println("Febrary");break;
                case 3:System.out.println("March");break;
                case 4:System.out.println("April");break;
                case 5:System.out.println("May");break;
                case 6:System.out.println("June");break;
                case 7:System.out.println("July");break;
                case 8:System.out.println("August");break;
                case 9:System.out.println("September");break;
                case 10:System.out.println("October");break;
                case 11:System.out.println("November");break;
                case 12:System.out.println("December");break;
            }
    
        }
    }
    
    ```
- 4、![在這里插入圖片描述](https://upload-images.jianshu.io/upload_images/24494503-e92f2d69dd2f106a?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    ```java
    package chapter03;
    
    import java.util.Scanner;
    
    public class Code_05 {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            System.out.print("Enter today's day: ");
            int number1 = input.nextInt();
            System.out.print("Enter the number of days elapsed since today: ");
            int number2 = input.nextInt();
            System.out.print("Today is ");
            method(number1);
            System.out.print(" and the future day is ");
            method(number2);
        }
        static void method(int n){
            switch (n){
                case 0:System.out.print("Sunday");break;
                case 1:System.out.print("Monday");break;
                case 2:System.out.print("Tuesday");break;
                case 3:System.out.print("Wednesday");break;
                case 4:System.out.print("Thursday");break;
                case 5:System.out.print("Friday");break;
                case 6:System.out.print("Saturday");break;
            }
        }
    }
    
    ```
- 5、[圖片上傳失敗...(image-b8f19-1601914568733)]
    ```java
    package chapter03;
    
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Code_08 {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            System.out.print("Enter three number(int): ");
            int a = input.nextInt();
            int b = input.nextInt();
            int c = input.nextInt();
            int[] arr = {a,b,c};
            Arrays.sort(arr);
            for(int i = 0; i < arr.length; i++){
                System.out.print(arr[i]+" ");
            }
        }
    }
    
    ```
- 6、![在這里插入圖片描述](https://upload-images.jianshu.io/upload_images/24494503-7ed774aa61746303?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    ```java
    package chapter03;
    
    public class Code_09 {
        public static void main(String[] args){
    
            java.util.Scanner input = new java.util.Scanner(System.in);
    
            System.out.print("Enter the first 9 digits of an ISBN as integer: ");
            int first9Digits = input.nextInt();
    
            int d9 = first9Digits %10;
            int d8 = first9Digits /10 % 10;
            int d7 = first9Digits /100 % 10;
            int d6 = first9Digits /1000 % 10;
            int d5 = first9Digits /10000 % 10;
            int d4 = first9Digits /100000 % 10;
            int d3 = first9Digits /1000000 % 10;
            int d2 = first9Digits /10000000 % 10;
            int d1 = first9Digits /100000000;
    
            int d10 = (int)((d1 *1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9)%11);
    
            if(d10 == 10)
                System.out.println("The ISBN-10 number is " +first9Digits+"X");
            else
                System.out.println("The ISBN-10 number is " +first9Digits+d10);
    
        }
    }
    
    ```
- 7、[圖片上傳失敗...(image-7c0eb1-1601914568733)]
    ```java
    package chapter03;
    
    import java.util.Random;
    import java.util.Scanner;
    
    public class Code_10 {
        public static void main(String[] args){
            Random r1 = new Random();
            int one = r1.nextInt(100);
            int two = r1.nextInt(100);
            System.out.print(one + " - " + two + " = ");
            Scanner input = new Scanner(System.in);
            int answer = input.nextInt();
            if (answer == one - two)
                System.out.println("You are right!");
            else
                System.out.println("You are wrong!");
        }
    }
    
    ```
- 8、![在這里插入圖片描述](https://upload-images.jianshu.io/upload_images/24494503-c339d7aece968de9?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    ```java
    package chapter03;
    
    import java.util.Scanner;
    
    public class Code_12 {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            System.out.print("Enter a three-digits integer: ");
            String str1 = input.nextLine();
            String str2 = "";
            for (int i = str1.length() - 1;i >= 0;i--){
                str2 += str1.charAt(i);
            }
            if (str1.equals(str2))
                System.out.println(str1 + " is a palindrome");
            else
                System.out.println(str1 + " is not a palindrome");
        }
    }
    
    ```
- 9、[圖片上傳失敗...(image-c9e8f5-1601914568734)]
    ```java
    package chapter03;
    
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Code_19 {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            System.out.print("Enter three integers: ");
            int a = input.nextInt();
            int b = input.nextInt();
            int c = input.nextInt();
            int[] arr = {a,b,c};
            Arrays.sort(arr);
            if (arr[0] + arr[1] > arr[2])
                System.out.println("legitimate");
            else
                System.out.println("not legitimate");
        }
    }
    
    ```
    - 10、[圖片上傳失敗...(image-56f103-1601914568734)]
    ```java
    package chapter03;
    
    import java.util.Random;
    
    public class Code_24 {
        public static void main(String[] args){
            Random r1 = new Random();
            Random r2 = new Random();
            int size = r1.nextInt(13);
            int color = r2.nextInt(4);
            switch (size){
                case 0:System.out.print("The card you picked is 1 of ");break;
                case 1:System.out.print("The card you picked is 2 of ");break;
                case 2:System.out.print("The card you picked is 3 of ");break;
                case 3:System.out.print("The card you picked is 4 of ");break;
                case 4:System.out.print("The card you picked is 5 of ");break;
                case 5:System.out.print("The card you picked is 6 of ");break;
                case 6:System.out.print("The card you picked is 7 of ");break;
                case 7:System.out.print("The card you picked is 8 of ");break;
                case 8:System.out.print("The card you picked is 9 of ");break;
                case 9:System.out.print("The card you picked is 10 of ");break;
                case 10:System.out.print("The card you picked is Jack of ");break;
                case 11:System.out.print("The card you picked is Queen of ");break;
                case 12:System.out.print("The card you picked is King of ");break;
            }
            switch (color){
                case 0:System.out.print("Clubs");break;
                case 1:System.out.print("Diamonds");break;
                case 2:System.out.print("Hearts");break;
                case 3:System.out.print("Spades");break;
            }
        }
    }
    
    ```
- 11、![在這里插入圖片描述](https://upload-images.jianshu.io/upload_images/24494503-d461a1f4b88bea8f?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    ```java
    package chapter03;
    
    public class Code_28 {
        public static void main(String[] args){
            java.util.Scanner input = new java.util.Scanner(System.in);
            System.out.print("Enter r1's center x-,y-cooordinates, width,and height:");
    
            double x1 = input.nextDouble();
            double y1 = input.nextDouble();
            double w1 = input.nextDouble();
            double h1 = input.nextDouble();
    
            System.out.print("Enter r2's center x-,y-coordinates, width,and height:");
    
            double x2 = input.nextDouble();
            double y2 = input.nextDouble();
            double w2 = input.nextDouble();
            double h2 =input.nextDouble();
    
            double xDistance = x1 -x2 >=0 ? x1-x2 : x2-x1;
            double yDistance = y1-y2 >=0? y1-y2 : y2-y1;
    
            if (xDistance <= (w1 - w2) / 2 && yDistance <= (h1 - h2) / 2)
                System.out.println("r2 is inside r1");
            else if (xDistance <= (w1 + w2) / 2 && yDistance <= (h1 + h2) / 2)
                System.out.println("r2 overlaps r1");
            else System.out.println("r2 does not overlap r1");
        }
    }
    
    ```
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容