Java SE練習題——求奇數

歡迎來到Java SE練習題頻道,我是Fishing,今天我帶來的練習題是(作題會有不足之處,可評論,說出更好的方法):java

經過鍵盤輸入兩個整數,計算這兩個整數之間的全部奇數之和,並輸出計算結果。

看到這題,我首先敲出了main函數。                : )函數

public static void main(String[] args) {
    // 代碼部分
}

 

首先,鍵盤輸入嘛,獲取控制檯的信息,import Scanner包,實例化對象:spa

import java.util.Scanner;

public class Test {

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args){
        // 代碼部分
    }

}

讀入兩個數:代碼規範

// 獲取信息
System.out.println("請輸入第一個整數:");
int i1 = sc.nextInt();
System.out.println("請輸入第二個整數:");
int i2 = sc.nextInt();

呵呵,我到這一步懵了。。。code

首先,一「堆」好的代碼不只要有代碼規範,還要有註釋、思路。我一想,要先判斷輸入的數的大小,在判斷小的數是否爲奇數,再用循環。。。對象

// 判斷小的數是否爲奇數
if (small % 2 == 1) {
    small++;
    small++;
} else {
    small++;
}

 而後,我有用了循環,將全部之間的奇數都列出來而後將返回值不斷增長,最後,呵呵,,,blog

        // 算出結果
        int result = 0;
        while (small < big) {

            result += small;

            // 加2
            small++;
            small++;

        }
        return result;

完美,,,get

完整代碼:class

import java.util.Scanner;

/**
 * 做者: Fishing
 * 時間: 2018-05-23
 * 概述: 經過鍵盤輸入兩個整數,計算這兩個整數之間的全部奇數之和,並輸出計算結果。
 */

public class Demo {

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        // 獲取信息
        System.out.println("請輸入第一個整數:");
        int i1 = sc.nextInt();
        System.out.println("請輸入第二個整數:");
        int i2 = sc.nextInt();

        // 判斷兩個數的大小
        if (i1 >= i2) {
            System.out.println(getResult(i2, i1));
        } else {
            System.out.println(getResult(i1, i2));
        }

    }

    private static int getResult(int small, int big) {
        // 判斷小的數是否爲奇數
        if (small % 2 == 1) {
            small++;
            small++;
        } else {
            small++;
        }

        // 算出結果
        int result = 0;
        while (small < big) {

            result += small;

            // 加2
            small++;
            small++;

        }
        return result;

    }

}

此次的題目分享就到這裏,謝謝看完。。。import

相關文章
相關標籤/搜索