Function 函數

/*!!函數內部不能再定義函數

* 函數定義
* 返回值類型 函數名(形式參數1,形式參數2){
* 函數體
* }
*   
 
函數的調用
函數名(實際參數); //相當於一個表達式
 
參數: 上層調用 向底層函數實現傳遞信息的方式
返回值:底層實現向  上層傳遞結果的方法 
 
*   */


//函數定義
//無參數 無返回值的函數
public static void triDisp(){
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}

//函數定義
//有參數 無返回值的函數
//功能:打印n行的三角形
public static void triDisp2(int n){ //在調用時    n=x 將實際參數的值賦值給n 
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}

//練習  打印一個m行 n列的矩形
public static void squareDisp(int m ,int n){
for (int i = 1; i <= m; i++) {
for (int j = 1; j <=n; j++) {
System.out.print("*");
}
System.out.println();
}

return ;//return 後面什麼都不加  相當於void
}

//練習:函數實現求解x!
//     僅僅負責運算
public static long factorial(int x){
long fac = 1;
for (int i = 1; i <= x; i++) {
fac *=i;
}
return fac;//返回值  決定了函數調用表達式的值
}

//練習:求給定的int數組的和 
//參數:int[] arr
//返回值:
public static int fun1(int[] arr){
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum+=arr[i];
}

return sum;
}

//練習:展示(打印) 一個給定的int 數組
//參數:int[] arr
//返回值: 
public static void fun2(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}

/*練習
* 給定一個英文句子,單詞之間用 1 個空格分開,
* 求出第 3 個單詞的偏移位置。
* 例如 “Professor du comes from Korea”的偏移位置是 10。  
* */
//參數: String line那句話    int n 第幾個單詞
//返回值:第n個單詞 的首字母的 偏移量
public static int findWorld(String line, int n){
int offset=0;
char[] arr = line.toCharArray();

int count=0;//以經幾次空格  n-1次時結束循環
for (int i = 0; i < arr.length ; i++) {
if (arr[i] == ' ') {
count++; //統計當前空格是第幾個
if (count == n-1) {
offset = i+1;
break;
}
}
}

return offset;
}



public static void main(String[] args) {
/*--------函數(方法)----------
* function  method
某種功能的代碼塊的集合
代指  從而簡化代碼
* */

/*

**
***
****
* */

//無參函數的調用
// triDisp();

/*........*/
//有參函數調用
// triDisp2(10);
// int x= 30;
// squareDisp(x, 5);
//
// int num1 = 12;
// int num2 = 3;
// System.out.println( factorial(num1/num2)  + 5); 


int[] arrObj = {1,2,3,4,5,6,7,8,-9};
System.out.println(fun1(arrObj));
fun2(arrObj);

String str = "Professor du comes from Korea";
System.out.println(findWorld(str, 100) );

}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章