JAVA入門 常見問題總結:第二章 知識點(2)流程控制

分支結構:

  1. 寫出結果:

    class Demo{
        public static void main(String[] args){
            int m=0,n=3;
            if(m>0)
            if(n>2)
            System.out.println("A");    
            else
            System.out.println("B");        
        }
    }
    //answer:沒有結果
    
  2. 實現對三個整數進行排序,輸出時按照從小到大的順序輸出。

  3. 從鍵盤分別輸入年、月、日,判斷這一天是當年的第幾天

    public class Test {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("輸入year:");
            int year = scanner.nextInt();
            System.out.println("輸入month:");
            int month = scanner.nextInt();
            System.out.println("輸入day:");
            int day = scanner.nextInt();
            int sumDay = 0;
            switch (month) {
            case 12:
            sumDay += 30;
            case 11:
            sumDay += 31;
            case 10:
            sumDay += 30;
            case 9:
                sumDay += 31;
            case 8:
                sumDay += 31;
            case 7:
                sumDay += 30;
            case 6:
                sumDay += 31;
            case 5:
                sumDay += 30;
            case 4:
                sumDay += 31;
            case 3:
                if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
                    sumDay += 29;
                else
                    sumDay += 28;
            case 2:
                sumDay += 31;
            case 1:
                sumDay += day;
            }
            System.out.println(year + "年" + month + "月" + day + "日是今年的第" + sumDay + "天");
        }
    }
    
  4. switch是否能作用在byte上,是否能作用在long上,是否能作用在String上
    答:switch(expr1)中,expr1是一個整數表達式。因此傳遞給 switch 和 case 語句的參數應該是
    int、 short、 char 或者 byte。long不能作用于swtich.JDK1.7新加入了String類型。

  5. 編寫程序,判斷給定的某個年份是否是閏年
    閏年的判斷規則如下:
    (1)若某個年份能被4整除但不能被100整除,則是閏年。
    (2)若某個年份能被400整除,則也是閏年。

     if((year % 4 ==0 && year % 100 != 0) || year % 400 == 0){}
    
  6. 要求用戶輸入兩個數a和b,如果a能被b整除或者a加b大于1000,則輸出a;否則輸出b。

  7. 編寫程序,從鍵盤接收整數參數.如果該數為1-7,打印對應的星期值,否則打印“非法參數”。

  8. 使用條件結構實現,如果用戶名等于字符‘青’,密碼等于數字‘123’,就輸出“歡迎你,青”,否則就輸出“對不起,你不是青”。
    提示:先聲明兩個變量,一個是char型的,用來存放用戶名,一個是int型的,用來存放密碼。

  9. ??求ax2+bx+c=0方程的根。
    a,b,c分別為函數的參數,
    如果:b2-4ac>0,則有兩個解;b2-4ac=0,則有一個解;b2-4ac<0,則無解;
    已知:x1=(-b+sqrt(b2-4ac))/2a
    X2=(-b-sqrt(b2-4ac))/2a

    System.out.println("求 ax^2 + bx + c = 0的解");
    
    Scanner scan = new Scanner(System.in);
    while (true) {
    
        int a, b, c;
        a = b = c = 0;
        //或 int a=0, b=0, c=0;
    
        System.out.println("請輸入a的值");
        if (scan.hasNextInt()) {
            a = scan.nextInt();
            if (a == 0) {
                System.out.println("此方程不是2元1次方程,解方程結束");
                return;
            }
        }
        System.out.println("請輸入b的值");
        if (scan.hasNextInt()) {
            b = scan.nextInt();
        }
        System.out.println("請輸入c的值");
        if (scan.hasNextInt()) {
            c = scan.nextInt();
        }
    
        System.out.println("a=" + a + ", b=" + b + ", c=" + c);
    
        double result = b*b - 4 * a * c;
        System.out.println(result);
        if (result < 0) {
            System.out.println("此方程無解");
    
        }else {
            System.out.println(Math.sqrt(result));
            double x1 = (-b + Math.sqrt(result))/(2*a);
            System.out.println("x1 = " + x1);
            if (result > 0) {
                double x2 = (-b - Math.sqrt(result))/(2*a);
                System.out.println("x2 = " + x2);
                System.out.println("此方程有2個解");
                return;
            }
            System.out.println("此方程只有一個解");
        }
    }
    
  10. 生成13位條形碼

```
Ean-13碼規則:第十三位數字是前十二位數字經過計算得到的校驗碼。
例如:690123456789
計算其校驗碼的過程為:
@前十二位的奇數位和6+0+2+4+6+8=26
@前十二位的偶數位和9+1+3+5+7+9=34
@將奇數和與偶數和的三倍相加26+34*3=128
@取結果的個位數:128的個位數為8
@用10減去這個個位數10-8=2
所以校驗碼為2
(注:如果取結果的個位數為0,那么校驗碼不是為10(10-0=10),而是0)
實現方法ean13()計算驗證碼,輸入12位條碼,返回帶驗證碼的條碼。
    例:輸入:692223361219輸出:6922233612192
```
```
//實現代碼
static void test1 () {

    Scanner scan = new Scanner(System.in);
    String numberString;

    while (true) {
        System.out.println("輸入12位條碼");
        if (scan.hasNext()) {
            numberString = scan.next();

            //if (number >= 10000000000L && number <= 99999999999L) {//為了讓編譯器直接識別較長的long型,需要直接使用"L"標明。
            if (numberString.length() == 12) {
                System.out.println(numberString);
                break;//退出循環
            }else {
                System.out.println("輸入位數錯誤");
            }
        }
    }

    int sum1 = 0;//奇數位的和
    int sum2 = 0;//偶數位的和

    for (int i = 0; i < 12; i++) {
        char letter = numberString.charAt(i);

        int iNumber = (int)letter - (int)'0';

        if (i%2 == 0) {
            //奇數位
            sum1 += iNumber;
        }else {
            //偶數位
            sum2 += iNumber;
        }
    }

    int checkCode = 10 - (sum1 + sum2 * 3) % 10;

    System.out.println("奇數位的和:" + sum1 + "\n偶數位的和:" + sum2 + "\n得到的校驗碼:" + checkCode);
    //其實應該分個字符串放進數組便利

    /*
    * 輸入12位條碼
    * 690123456789
    690123456789
    奇數位的和:26
    偶數位的和:34
    得到的校驗碼:2

    輸入12位條碼
    692223361219
    692223361219
    奇數位的和:15
    偶數位的和:31
    得到的校驗碼:2
    * */
```
  1. 循環結構:

    //What is the result when you compile and run the following code? 
    public class Test{
        public void method(){
            for(int i = 0; i < 3; i++) {
               System.out.print(i);
           }
           System.out.print(i);
        }
    }
    

    A. 0122 B. 0123 C. compile error D. none of these

    答案:C

  2. 打印1-100之間13的倍數,使用for循環

    static void test2() {
    
        for (int i = 1; i < 101; i++) {
            if (i % 13 == 0) {
                System.out.println(i);
            }
        }
        //共需執行100 * 100 = 10000次
    
        for (int i = 1; i <= 101 / 13; i++) {
            System.out.println(13 * i);
        }
        //只需執行101/13次,遠遠小于第一種
    
        //13//26//39//52//65//78//91
    }
    
  3. 使用雙重循環打印20 * 8的矩形,使用for循環實現

    static void test3() {
    
        for (int i = 0; i < 8; i++) {
            String string = "";
            for (int j = 0; j < 20; j++) {
                string = string + "*";
    
            }
            System.out.println(string);//默認換行
        }
    
    }
    
  4. 用for循環計算1000以內奇數的和

  5. 1)輸入長和寬,輸出長方形,如:輸入4和3, 將輸出如下圖形

2)輸入高度,輸出直角三角形。如:輸入4, 將輸出如下圖形

3)輸入高度,輸出倒直角三角形。如:輸入4, 將輸出如下圖形

  1. 打印九九乘法表

  2. 3000米長的繩子,每天減一半。問多少天這個繩子會小于5米?不考慮小數。

    public static void main(String[] args) {
        int day = 0;
        for (int x = 3000; x >= 5; x /= 2) {
            day++;
        }
        System.out.println("day=" + day);
        /*
         * 方法二: 
         * day = 0; 
         * for(int x=3000; x>=5; day++) { 
         *      x = x/2; 
         * }
         * System.out.println(day);
         */
    }
    
  3. 打印1-100之間13的倍數,使用continue語句

  4. 混合結構練習
    寫出結果

    public class Demo{ 
        public static void main(String []args){ 
            int i = 0, j = 5; 
            tp: for (;;){ 
                i++; 
                for(;;){
                    if(i > j--)
                    break tp; 
                }
            } 
            System.out.println("i = " + i + ", j = "+ j);   //i=1,j=-1;
        } 
    }
    
  5. 輸出從1到100之間所有不能被3整除的數;并輸出這些整數的和

  6. 輸入兩個正整數m和n,求其最大公約數和最小公倍數

    int m = 12, n = 28;
    //獲取m和n的較大值
    int max = (m > n)? m : n;
    //獲取m和n的較小值
    int min = (m < n)? m : n;
    
    //求m和n的最大公約數
    for(int i = min;i >= 1;i--){
        if( m % i == 0 && n % i == 0){
            System.out.println("m和n的最大公約數是:" + i);
            break;
        }
    }
    //求m和n的最小公倍數
    for(int i = max;i <= m * n;i++){
        if( i % m == 0 && i % n == 0){
            System.out.println("m和n的最小公倍數是:" + i);
            break;
        }
    }
    
  1. 根據指定月份,打印該月份所屬的季節
    分別使用if-else if-else語句和switch-case語句:
    3,4,5 春季 6,7,8 夏季 9,10,11 秋季 12, 1, 2 冬季

    [answer]
    if(x==3 || x==4 || x==5)
        System.out.println(x+"春季");
    else if(x==6 || x==7 || x==8)
        System.out.println(x+"夏季");
    else if(x==9 || x==10 || x==11)
        System.out.println(x+"秋季");
    else if(x==12 || x==1 || x==2)
        System.out.println(x+"冬季");
    else
        System.out.println(x+"月份不存在");
    
    [第二種]
    if(x>12 || x<1)
        System.out.println(x+"月份不存在");
    else if(x>=3 && x<=5)
        System.out.println(x+"春季");
    else if(x>=6 && x<=8)
        System.out.println(x+"夏季");
    else if(x>=9 && x<=11)
        System.out.println(x+"秋季");
    else
        System.out.println(x+"冬季"); 
    
    [第3種]
    public static void main(String[] args) {
        int x = 4;
        switch(x){
            case 3:
            case 4:
            case 5:
                System.out.println(x+"春季");
                break;
            case 6:
            case 7:
            case 8:
                System.out.println(x+"夏季");
                break;
            case 9:
            case 10:
            case 11:
                System.out.println(x+"秋季");
                break;
            case 12:
            case 1:
            case 2:
                System.out.println(x+"冬季");
                break;
            default:
                System.out.println("nono");
        }
    }
    
  2. 已知學生成績以100分為滿分,共分5個等級:A,B,C,D,E。90~100為等級A,80~89為等級B,70~79為等級C,60~69為等級D,0~59為等級E。

    要求定義一個成績變量,當成績變化時,可直接知道該成績對應的等級。
    例如:當成績為100時,該學生的等級時A。
    class LevelDemo{
        //定義一功能,通過給定分數,獲取該分數對應的等級。
        public static void main(String[] args){
            int num = 89;
            if(num>=90 && num<=100)
                System.out.println("level = A");
            else if(num>=80 && num<=89)
                System.out.println("level = B");
            else if(num>=70 && num<=79)
                System.out.println("level = C");
            else if(num>=60 && num<=69)
                System.out.println("level = D");
            else
                System.out.println("level = E");
        }
    }
    
  3. 1)打印1~100之間 6的倍數的個數;
    2)求出1~100之間,既是3又是7的倍數的自然數出現的次數?

    public static void main(String[] args) {
            int count1 = 0,count2 = 0;
            for (int x = 1; x <= 100; x++) {
                if (x % 6 == 0){
                    count1++;
                }
                if(x % 3 == 0 && x % 7 == 0){
                    count2++;
                }
            }
            System.out.println("count1=" + count1);
            System.out.println("count2=" + count2);
    }
    
  4. 求調和級數中從第多少項開始和的值大于10
    調和級數的第n項形式為:1+1/2+1/3+…+1/n

    public static void main(String[] args) {
        double sum = 0.0;
        int i = 1;
        while (true) {
            sum += 1.0 / i;
            if (sum > 10) {
                break;
            }
            i++;
        }
        System.out.println(i);
    }
    
  5. 打印如下的圖形

       *
       * * *
       * * * * *
       * * * * * * *
       * * * * *
       * * *
       *
    for (int i = 0; i < 7; i++) {
        if (i < 4) {
            for (int j = 0; j < 2 * i + 1; j++) {
                System.out.print("* ");
            }
            System.out.println();
        } else {
            for (int k = 0; k < 13 - 2 * i; k++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
    
  6. 【拓展】打印如下的圖形

        * 
       * * 
      * * * 
     * * * * 
    * * * * * 
     * * * * 
      * * * 
       * * 
        * 
    // 上半部分
    for (int i = 0; i < 5; i++) {
        // 輸出“-”
        for (int j = 0; j < 4 - i; j++) {
            System.out.print(" ");
        }
    
        // 輸出“* ”
        for (int k = 0; k < i + 1; k++) {
            System.out.print("* ");
        }
        System.out.println();
    }
    // 下半部分
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < i + 1; j++) {
            System.out.print(" ");
        }
        for (int k = 0; k < 4 - i; k++) {
            System.out.print("* ");
        }
        System.out.println();
    
    }
    
    //解法2
    static void test6() {
    
        Scanner scan = new Scanner(System.in);
    
        System.out.println("請輸入菱形的規模,僅限與奇數");
    
        int startsCount = 0;
        if (scan.hasNextInt()) {
            startsCount = scan.nextInt();
        }
    
        if (startsCount % 2 == 0) {
            System.out.println("非奇數");
            return;
        }
    
        //打印目標
        int a = startsCount / 2 + 1;
    
        for (int i = 0; i < startsCount; i++) {
            String currentString = "";
            if (i < a) {//上部
                for (int j = 0; j < startsCount / 2 - i; j++) {
                    currentString += " ";
                }
                for (int j = 0; j <= i; j++) {
                    currentString += "* ";
                }
            } else {//下部
                /*
                * 中間星星的總數 = 總數/2 +1;
                * 空格數 = 中間星星數 - (行數相對于中間的相對值);
                * */
                for (int j = 0; j < i-a+1; j++) {
                    currentString += " ";
                }
                for (int j = a - (i-a+1); j > 0; j--) {
                    currentString += "* ";
                }
            }
            System.out.println(currentString);
        }
    
    }
    
  7. 拓展:打印如下的圖形

    **********         
    ****  ****         
    ***    ***         
    **      **         
    *        *        
    **      **
    ***    ***
    ****  ****
    **********
    
    //code 
    static void test7() {
    
        int rows = 9;
    
        for (int i = 0; i < rows; i++) {
            String starsString = "";
            if (i <= rows/2) {
                //上部
                //分左右
                for (int j = 0; j < rows+1; j++) {
                    //總數 rows+1
                    //星星數 2*i
                    if (j >= (rows+1)/2-i && j< (rows+1)/2+i) {
                        starsString += " ";
                    }else {
                        starsString += "*";
                    }
                }
            } else {
                //下部
                for (int j = 0; j < rows+1; j++) {
                    if (j >= (i-rows/2)+1 &&  j < (rows+1)-((i-rows/2)+1)) {
                        starsString += " ";
                    } else {
                        starsString += "*";
                    }
                }
            }
            System.out.println(starsString);
        }
    
    }
    
  8. 編寫程序,打印100-200之間的質數

    for (int i = 100; i <= 200; i++) {
        int count = 0;//記錄當前i的因數個數
        for (int j = 1; j <= i; j++) {
            if (i % j == 0) {
                count ++;
                if (count > 2) {
                    continue;
                }
            }
        }
        if (count == 2) {
            System.out.println("素數" + i);
        }
    }
    
  9. 一個數如果恰好等于它的因子之和,這個數就稱為"完數"
    (因子:除去這個數本身正的約數)
    例如6=1+2+3.編程 找出1000以內的所有完數

    public class WanShu {
        //方法2 自寫
        for (int i = 1; i <= 1000; i++) {
            int sum = 0;
            for (int j = 1; j < i; j++) {
                if (i % j == 0) {
                    sum += j;
                }
            }
            if (sum == i) {
                System.out.println(i);
            }
        }
        //方法1 Demo
        static int count;
        public static void main(String[] args) {
            for (int i = 1; i <= 1000; i++) {
                int factor = 0;
                for (int j = 1; j < i; j++) {
                    if (i % j == 0)
                        factor += j;
                }
                if (factor == i) {
                    System.out.println(i);
                    count++;
                }
            }
            System.out.println("1-1000之間的完數個數為:" + count);
        }
    }
    
  1. ??(數組暫時沒學)寫一個程序,找出4位數的所有吸血鬼的數字
    例如:1260=21*60
    1827=21*87

    public class Test1 {
        public static void main(String[] args) {
            for (int num = 1001; num < 10000; num++) {
                math(num);
            }
        }
    
        public static void math(int num) {
            int[] temp1 = new int[2];
            int[] temp2 = new int[2];
    
            int a = num / 1000;
            int b = num / 100 % 10;
            int c = num / 10 % 10;
            int d = num % 10;
            int[] data = { a, b, c, d };
            for (int i = 0; i < data.length; i++) {
                for (int j = 0; j < data.length; j++) {
                    if (i == j) {
                        continue;
                    }
                    temp1[0] = data[i];
                    temp1[1] = data[j];
                    for (int m = 0; m < data.length; m++) {
                        if (m != i && m != j) {
                            temp2[0] = data[m];
                            for (int n = 0; n < data.length; n++) {
                                if (n != i && n != j && n != m) {
                                    temp2[1] = data[n];
                                    multi(data, temp1, temp2);
                                }
                            }
                        }
                    }
                }
            }
        }
    
        public static int toInt(int[] temp) {
            int m = 0;
            int[] temp1 = new int[temp.length];
            for (int i = 0; i < temp.length; i++) {
                temp1[i] = temp[i] * (int) Math.pow(10, temp.length - 1 - i);
            }
            for (int i = 0; i < temp1.length; i++) {
                m += temp1[i];
            }
            return m;
        }
    
        public static void multi(int[] temp, int[] temp1, int[] temp2) {
            int i = toInt(temp1);
            int j = toInt(temp2);
            int k = toInt(temp);
            if (k == i * j) {
                System.out.println(k + "=" + i + "*" + j);
            }
        }
    }
    
  2. 輸出所有的水仙花數。所謂水仙花數是指一個3位數,其各個位上數字立方和等于其本身。

    例如: 153 = 1*1*1 + 3*3*3 + 5*5*5 
    class ShuiXianHua {
        public static void main(String[] args) {
            for (int i = 100; i < 1000; i++) {// 實現所有的三位數的一個遍歷
                int j1 = 0;
                int j2 = 0;
                int j3 = 0;
                j1 = i / 100;// 百位
                j2 = (i - 100 * j1) / 10;// 十位
                j3 = i - 100 * j1 - 10 * j2;// 個位
    
                if (i == j1 * j1 * j1 + j2 * j2 * j2 + j3 * j3 * j3) {
                    System.out.println("此數值為滿足條件的水仙花數:" + i);
                }
            }
        }
    }
    
  3. 山上有一口缸可以裝50升水,現在有15升水。老和尚叫小和尚下山挑水,每次可以挑5升。問:小和尚要挑幾次水才可以把水缸挑滿?通過編程解決這個問題。
    提示:
    (1) 用整型變量water表示水缸里的水“int water = 15;”。
    (2) 用整型變量l表示小和尚下山挑水的次數“int l = 0;”。
    (3) 分析循環條件(水少于50升),循環操作(水增加5升,挑水次數增加1)。
    (4) 套用while循環(或do-while循環)寫出代碼。

  4. 實現判斷一個4位整數,統計出此整數里面包含多少個偶數,多少個奇數的功能

  5. 開發一款軟件,根據公式(身高-108)*2=體重,可以有10斤左右的浮動。來觀察測試者體重是否合適。

  6. 有3個整數,給出提示信息:
    能否創建三角形;兩邊之和大于第三邊 三個條件都要寫
    如果能構建三角形,提示是直角三角形還是等邊三角形等腰三角形還是普通三角形;
    最后輸出三角形面積;

  7. 在JAVA中,如何跳出當前的多重嵌套循環?
    答:用break; return 方法。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 【程序1】 題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一對兔...
    開心的鑼鼓閱讀 3,344評論 0 9
  • 【程序1】 題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一...
    阿里高級軟件架構師閱讀 3,307評論 0 19
  • Java經典問題算法大全 /*【程序1】 題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子...
    趙宇_阿特奇閱讀 1,895評論 0 2
  • 【程序1】 題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一對兔...
    葉總韓閱讀 5,162評論 0 41
  • 生活到現在 時常感覺很累,很疲憊 婚姻,帶給我什么 兩個孩子,一個像“兒子”般的男人 還有一屋子由陌生成為熟悉的家...
    第九夫人閱讀 1,802評論 27 17