函數
定義:函數就是在類中具有特點功能的一頓獨立小程序。也稱爲方法。
格式:
修飾符 返回值類型 函數名(參數類型 形式參數1,參數類型 形式參數2,…){
執行語句;
return 返回值;
}
返回值類型:函數運行後的結果的數據類型。
參數類型:是形式參數的數據類型。
形式參數:是一個變量,用於存儲調用函數時傳遞給函數的實際參數。
實際參數:傳遞給形式參數的具體數值。
return : 用於結束函數。
返回值:該函數運算後的結果,該結果會返回給調用者。
特點:
1.將功能封裝,便於對功能進行復用。
2.只有函數被調用纔會執行。
3.對於函數沒有具體返回值的時,返回值類型用關鍵字void表示。那麼該函數中的 return語句可以省略不寫。
注意:
1.函數中只能調用函數,不可以在函數內部定義函數。
2.定義函數時,函數的結果應該返回給調用者,交由調用者處理。
3.函數只爲實現它所需功能,不要實現不需要的功能。
4.輸出語句只能對有返回值類型的函數調用後打印,不能對沒有返回值類型的函數 打印。
5.不要將代碼都放在main函數裏。
應用:
兩個明確:
明確要定義的功能最後的結果是什麼?明確返回值類型
明確在定義該功能的過程中,是否需要未知內容參與運算。明確參數列表
函數的重載
概念:在同一個類中,允許存在一個以上的同名函數,只要他們的參數個數和參數類型
不同即可。
特點:與返回值類型無關,只看參數列表:參數個數和參數類型。
好處:方便閱讀,優化了程序設計。
函數練習
/*
函數練習
*/
class HanShuTest {
public static void main(String[] args) {
juXing(2,3);
System.out.println("————————————————");
getMax(34,6,45);
System.out.println("————————————————");
System.out.println(Max(7,3,5));
System.out.println("————————————————");
ifLiu(60);
System.out.println("————————————————");
chengFaBiao();
System.out.println("————————————————");
chengFaBiao(5);
}
/*
1,for的嵌套循環打印矩形用函數封裝起來,根據所傳參數打印行和列
*/
public static void juXing(int a,int b){
for (int x = 1; x <= a;x++ ){
for (int y = 1; y <= b;y++ ){
System.out.print("0");
}
System.out.println();
}
}
/*
定義一個功能獲取三個整數中的最大數
*/
public static void getMax(int a,int b,int c){
if (a > b){
if (a > c){
System.out.println(a);
}else if (b > c){
System.out.println(b);
}else if (c > a){
System.out.println(c);
}else{
System.out.println("相等");
}
}
}
public static int Max(int a,int b,int c){
int tmop = (a > b) ? a : b;
return tmop = (tmop > c) ? tmop : c;
}
/*
定義一個方法求一個數的十六進制表現形式
*/
public static void ifLiu(int x){
while (x != 0){
int nun = x & 15;
if (nun > 9){
System.out.println((char)(nun - 10 + 'a'));
}else {
System.out.println(x);
}
x = x >>> 4;
}
}
/*
打印99乘法表的重載方法
*/
public static void chengFaBiao(){
for (int x = 1; x <= 9;x++ ){
for (int y = 1; y <= x;y++ ){
System.out.print(y+"x"+x+"="+x*y+'\t');
}
System.out.println();
}
}
public static void chengFaBiao(int num){
for (int x = 1; x <= num;x++ ){
for (int y = 1; y <= x;y++ ){
System.out.print(y+"x"+x+"="+x*y+'\t');
}
System.out.println();
}
}
}