iT邦幫忙

0

重新開始學java-方法

wei 2023-04-15 19:56:47604 瀏覽
  • 分享至 

  • xImage
  •  

多次定義多次使用>通過方法解決(改為一次定義多次使用)
如 求兩個數組各自的最大值

int[] array1 = {300, 400, 500, 100, 1000, 50};
int max1 = array1[0];//
for (int i = 0; i < array1.length; i++) {
if (max1 < array1[i]) {
max1 = array1[i];
}
}
System.out.println("最大值:" + max1);
//--------------------------------------------------
int[] array2 = {300, 400, 500, 100, 1000, 50};
int max2 = array2[0];
for (int i = 0; i < array2.length; i++) {
if (max2 < array2[i]) {
max2 = array2[i];
}
}
System.out.println("最大值:" + max2);

好處:使用方法可以只定義一次,多次使用

[訪問修飾符] 返回值類型 方法名([參數]){
方法
}

訪問修飾符:控制當前內容可見的範圍
返回值類型:
沒有返回值類型,用void表示,如果遇到條件需要退出則用return
有返回值則要寫返回值類型,並在結束前加上return表示退出

方法有四種形式

  1. 無參無返回值
  2. 有參無返回值
  3. 無參有返回值
  4. 有參有返回值

求最大值可改寫為

static int getMaxByArray(int[] arr){
        int max = arr[0];
        for(int i=0;i<arr.length;i++){
            if(max<arr[i]){
                max = arr[i];
            }
        }
        System.out.println(max);
        return max;
    }

方法的重載
當參數個數或類型不同時,可以用同方法表示這個功能,只需要用這個方法就滿足不同的需求

    static int sum(int a, int b) {
        //int result = a + b;
        return a + b;//返回传入数据的运算结果
    }
    static int sum(int a, int b, int c) {
        return a + b + c;
    }
    static double sum(double a, double b) {
        return a + b;
    }
    
    public static void main(String[] args) {
       int r = sum(10, 20);
        System.out.println(r);
       int r1 = sum(10, 20,30);
        System.out.println(r1);
       int r2 = sum(1.23, 2.2);
        System.out.println(r1);
    }


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言