本文共 3876 字,大约阅读时间需要 12 分钟。
class Tool { int[] arr = {8, 54, 3, 47, 148, 77, 56, 55, 20}; public void countSum(int[] array) { int oddSum = 0; int evenSum = 0; for (int num : array) { if (num % 2 == 0) { evenSum += num; } else { oddSum += num; } } System.out.println("奇数和为:" + oddSum + "\n" + "偶数和为:" + evenSum); } public void sort(int[] array) { // 实现冒泡排序,从大到小排序 for (int i = 0; i < array.length - 1; i++) { for (int j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j+1]) { int temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } } } System.out.println("排序后的数组为:" + Arrays.toString(array)); }}public class Main { public static void main(String[] args) { int[] arr = {8, 54, 3, 47, 148, 77, 56, 55, 20}; Tool tool = new Tool(); tool.countSum(arr); tool.sort(arr); }} interface Computer { int compute(int num1, int num2);}class Add implements Computer { @Override public int compute(int num1, int num2) { return num1 + num2; }}class Subtract implements Computer { @Override public int compute(int num1, int num2) { return num1 - num2; }}class Multiply implements Computer { @Override public int compute(int num1, int num2) { return num1 * num2; }}class Divide implements Computer { @Override public int compute(int num1, int num2) { if (num2 == 0) { System.out.println("除数不能为零"); return 0; } return num1 / num2; }}class Calculator { public void performCalculations(Computer operation, int a, int b) { operation.compute(a, b); }}public class Main { public static void main(String[] args) { Calculator calc = new Calculator(); calc.performCalculations(new Add(), 10, 5); calc.performCalculations(new Subtract(), 20, 10); calc.performCalculations(new Multiply(), 3, 4); calc.performCalculations(new Divide(), 8, 2); }} class Tool { int[] numbers = {8, 54, 3, 47, 148, 77, 56, 55, 20}; void countSum() { int evenSum = 0; int oddSum = 0; for (int num : numbers) { if (num % 2 == 0) { evenSum += num; } else { oddSum += num; } } System.out.println("偶数和为:" + evenSum + "\n奇数和为:" + oddSum); } void sortArray() { for (int i = 0; i < numbers.length - 1; i++) { for (int j = 0; j < numbers.length - 1 - i; j++) { if (numbers[j] > numbers[j + 1]) { int temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } System.out.println("排序后的数组:" + Arrays.toString(numbers)); }}public class Main { public static void main(String[] args) { Tool tool = new Tool(); tool.countSum(); tool.sortArray(); }} class SortingTool { int[] array = {3, 6, 2, 8, 1}; void sort() { for (int i = 0; i < array.length - 1; i++) { for (int j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } System.out.println("排序后的数组:" + Arrays.toString(array)); }}public class Main { public static void main(String[] args) { SortingTool tool = new SortingTool(); tool.sort(); }} 转载地址:http://mkhfk.baihongyu.com/