天天看點

# java學習筆記 2020 2/7(九)慕課網 使用方法方法看到最後的幫忙點個贊👍🙏 謝謝!

方法

定義方法 Java

通路修飾符 傳回值類型 方法名(參數清單){

方法體;

}

public void show(){

System.out.println(“你們好!”);

}

  • 注意哦:

1、 方法體放在一對大括号中,實作特定的操作

2、 方法名主要在調用這個方法時使用,需要注意命名的規範,一般采用第一個單詞首字母小寫,其它單詞首字母大寫的形式

調用方法

  • main中建立類的對象 通過 對象名.方法名()調用
  • helloWorld hello = new HelloWorld();
  • hello.show();

自定義方法 有無參 和有無傳回值;

傳回類型 無傳回值void; 有傳回值 方法體中需添加 return;

根據方法是否帶參、是否帶傳回值,可将方法分為四類:

Ø 無參無傳回值方法

public void show(){

System.out.println(“你們好”);

}

Ø 無參帶傳回值方法

public int calcSum(){

int a = 5;

int b = 9;

int sum= a+b;

return sum;

}

不容忽視的“小陷阱”:

1、 如果方法的傳回類型為 void ,則方法中不能使用 return 傳回值!

# java學習筆記 2020 2/7(九)慕課網 使用方法方法看到最後的幫忙點個贊👍🙏 謝謝!

2、 方法的傳回值最多隻能有一個,不能傳回多個值

# java學習筆記 2020 2/7(九)慕課網 使用方法方法看到最後的幫忙點個贊👍🙏 謝謝!

3、 方法傳回值的類型必須相容,例如,如果傳回值類型為 int ,則不能傳回 String 型值

# java學習筆記 2020 2/7(九)慕課網 使用方法方法看到最後的幫忙點個贊👍🙏 謝謝!

功能:輸出學生年齡的最大值

* 定義一個無參的方法,傳回值為年齡的最大值
           

方法一:

public int getMaxAge() {

int[] ages ={18,23,21,19,25,29,17};

int max = ages[0];

for (int i=1;i<ages.length;i++){

if(max<ages[i])

max=ages[i];

}

return max;

}

方法二:

public int getMaxAge() {

int[] ages ={18,23,21,19,25,29,17};

Arrays.sort(ages);

int max = ages[ages.length-1];

return max;

}

定義一個無參的方法,傳回值為年齡的最大值

Ø 帶參無傳回值方法

一定不可忽視的問題:

1、 調用帶參方法時,必須保證明參的數量、類型、順序與形參一一對應

# java學習筆記 2020 2/7(九)慕課網 使用方法方法看到最後的幫忙點個贊👍🙏 謝謝!

2、 調用方法時,實參不需要指定資料類型,如

# java學習筆記 2020 2/7(九)慕課網 使用方法方法看到最後的幫忙點個贊👍🙏 謝謝!

3、 方法的參數可以是基本資料類型,如 int、double 等,也可以是引用資料類型,如 String、數組等

# java學習筆記 2020 2/7(九)慕課網 使用方法方法看到最後的幫忙點個贊👍🙏 謝謝!

4、 當方法參數有多個時,多個參數間以逗号分隔

# java學習筆記 2020 2/7(九)慕課網 使用方法方法看到最後的幫忙點個贊👍🙏 謝謝!

Ø 帶參帶傳回值方法

功能:将考試成績排序并輸出,傳回成績的個數

* 定義一個包含整型數組參數的方法,傳入成績數組

* 使用Arrays類對成績數組進行排序并輸出

* 方法執行後傳回數組中元素的個數

*/

HelloWorld hello = new HelloWorld();

int[] scores={79,52,98,81};

hello.sort(scores);

public int sort(int[] scores){

Arrays.sort(scores);

System.out.println(Arrays.toString(scores));

//傳回數組中元素的個數

return scores.length;

}

看到最後的幫忙點個贊👍🙏 謝謝!
# java學習筆記 2020 2/7(九)慕課網 使用方法方法看到最後的幫忙點個贊👍🙏 謝謝!