/* 來自第4章第2節:010402_【第4章:數組與方法】_方法的聲明及使用 */
1、方法的定義
類的命名規范:“全部單詞的首字母必須大寫”。方法的命名規范:“第一個單詞的首字母小寫,之后每個單詞的首字母大寫”。
2、無返回值的方法
如果在返回值類型上寫的是void,則表示此方法沒有返回值,則就不能使用return返回內容。
例:
public class MethodDemo01 { public static void main(String[] args) { printInfo(); printInfo(); printInfo(); System.out.println("Hello World!"); } //此處由於此方法是由main方法直接調用所以一定要加上public static public static void printInfo(){ char c[] = {'H','e'}; //定義一個字符數組 for(int x=0;x<c.length;x++){ //循環輸出 System.out.println(c[x]); } System.out.println(""); //換行 } }
運行結果:
H
e
H
e
H
e
Hello World!
3、有返回值的方法
如果需要一個方法有返回值,則直接在返回值類型處寫上返回值的類型即可。
例:
public class MethodDemo02 { public static void main(String[] args) { int one = addOne(10,20); //調用整型的加法操作 float two = addTwo(10.3f,13.3f); //調用浮點數的加法操作 float three = addThree(1,2); System.out.println("addOne的計算結果:" + one); System.out.println("addTwo的計算結果:" + two); System.out.println("addThree的計算結果:" + three); } //定義方法,完成兩個數字的相加操作,方法返回一個int型數據 public static int addOne(int x,int y){ int temp = 0; //方法中的參數,是局部變量 temp = x + y; //執行加法計算 return temp; //返回計算結果 } //定義方法,定義兩個數字的相加操作,方法的返回值是一個float型數據 public static float addTwo(float x,float y){ float temp = 0; //方法中的參數,是局部變量 temp = x + y; return temp; } public static float addThree(int x,int y){ float temp = 0; //方法中的參數,是局部變量 temp = x + y; return temp; } }
運行結果:
addOne的計算結果:30 addTwo的計算結果:23.6 addThree的計算結果:3.0