(一)方法的重载:在一个类中,方法名称相同,只有参数列表不同的方法叫方法的重载
public class T0931Demo01 {
public static void main(String[] args) {
/**求2个数的最大值
* 求3个数的最大值
* 求4个数的最大值
* 求5个数的最大值
*/
int max= sort(1, 2, 4, 9, 8);
System.out.println(max);
//求两个数的最大值
public static int sort(int a,int b) {
return(a > b)?a:b;
}
//求三个数的最大值
public static int sort(int a,int b, int c) {
//使用已经写好的俩个数求最大值的方法
int max =sort(a, b);
return sort(max, c);
//return(max > c)?max:c;
}
public static int sort(int a,int b, int c,int e) {
//使用已经写好的三个数求最大值的方法
int max =sort(a, b,c);
return sort(max, e);
}
public static int sort(int a,int b, int c,int e,int f) {
//使用已经写好的四个数求最大值的方法
int max =sort(a, b,c,e);
return sort(max, e);
}
(二)数组 :用来盛放变量的容器 ,根据下标存放数据,下标从0开始。
数组的定义 int[] arr = new int [x]; int[]arr = new int[]{1,2,3,4};
语法糖 int[] arr = {1,2,3,4};
数组的长度一旦给定就不可以改变;
数组异常
// 数组越界异常 ArrayIndexOutOfBoundsException
// 空指针异常 NullPointerException
(三)遍历数组
public static void ergodic(int array[]) {
System.out.print("[");
for (int i = 0; i < array.length - 1; i++) {
System.out.print(array[i] + ",");
}
System.out.println(array[array.length - 1] + "]");
}
(四)数组排序
选择排序
public static void sort(int arr[]) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i; j < arr.length - 1; j++) {
if (arr[i] > arr[j + 1]) {
int temp = arr[i];
arr[i] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
冒泡排序
public static void mppx(int arr[]) {
for (int i = 0; i < arr.length-1; i++) {
for (int j = 0; j < arr.length-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}