欢迎访问宙启技术站
智能推送

使用Java编写的十个最基本的函数

发布时间:2023-07-03 23:34:03

1. 计算两个数的和

public static int add(int a, int b) {
    return a + b;
}

2. 判断一个数是正数、负数还是零

public static String checkNumber(int num) {
    if (num > 0) {
        return "Positive";
    } else if (num < 0) {
        return "Negative";
    } else {
        return "Zero";
    }
}

3. 判断一个数是否为素数

public static boolean isPrime(int num) {
    if (num <= 1) {
        return false;
    }
    for (int i = 2; i <= Math.sqrt(num); i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

4. 计算一个数的阶乘

public static int factorial(int num) {
    int result = 1;
    for (int i = 1; i <= num; i++) {
        result *= i;
    }
    return result;
}

5. 判断一个字符串是否为回文

public static boolean isPalindrome(String str) {
    int left = 0;
    int right = str.length() - 1;
    while (left < right) {
        if (str.charAt(left) != str.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

6. 对一个整数数组进行排序(升序)

public static void sortArray(int[] arr) {
    for (int i = 0; i < arr.length - 1; i++) {
        for (int j = 0; j < arr.length - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

7. 求一个整数数组中的最大值

public static int findMaxValue(int[] arr) {
    int max = arr[0];
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

8. 计算一个字符串中某个字符出现的次数

public static int countCharOccurrences(String str, char target) {
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == target) {
            count++;
        }
    }
    return count;
}

9. 判断一个字符串是否为数字

public static boolean isNumeric(String str) {
    try {
        Double.parseDouble(str);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

10. 判断一个年份是否为闰年

public static boolean isLeapYear(int year) {
    if (year % 400 == 0) {
        return true;
    }
    if (year % 100 == 0) {
        return false;
    }
    return year % 4 == 0;
}

以上是十个最基本的函数,涵盖了数学计算、逻辑判断、字符串操作和数组操作等常见领域。在实际的编程中,这些函数常常作为基础函数被调用,使代码更加简洁、高效。