天天看點

Java基礎學習筆記二

1.方法:

1.1引入方法的概念

定義:方法是可以看成是一個獨立完成某個功能的一段代碼定義:方法是可以看成是一個獨立完成某個功能的一段代碼

1.2方法的基本格式

①文法結構:

修飾符 傳回值類型 方法名(變量1,變量2){

方法體

}

注意:

Java基礎學習筆記二

②調用方法的時候,形參必須要與實參一緻(類型  個數  順序)

③方法簽名:方法名+參數清單

④一個類中不能有兩個同樣的方法簽名(注意不是方法名,是方法簽名)

1.3方法的傳回值類型

①如果傳回值是void類型,内部不需要(也不能)return 一個值

②如果方法傳回值是void類型,是不能直接列印與接收的

1.4方法的重載(重點掌握)

1.4.1概念:在一個類中有多個重名的方法,方法名相同、傳回值相同。

1.4.1特點:在同一個類中,名字相同,但是參數清單不同

2.數組:用來存放資料

·2.1一維數組定義及寫法(★★★)

數組類型[] 數組名,例:

Int[] ages = new int[3];

int[] ages={116,17,18}兩種方法都可以,我習慣用第二種。

·2.2二維數組

在一維數組"【】"後加[]如:int [] [] a = new int[3][5];二維數組實質是對一維數組的延申,計算機中都是采用一維線性對資料存儲的。如:

/*int a[6] = {0, 1 ,2, 3, 4, 5}; // 一維數組

int b[2][3]; // 二維數組

int m = 2, n = 3;

for (int i = 0; i < m; i++)

{

for (int j = 0; j < n; j++)

{

b[i][j] = a[i*n + j];

}

}*/

把一維數組a轉化成了二維數組b;

練習:1.設計一個求多個整數積的方法

package fill;

public class Demo_01 {

 public static void main(String[]args)

 {

  Demo_01.Multiply(1,2,3,4);

  Demo_01.Multiply(5,6,7,8); 

 }

 public static void Multiply(int i,int j,int k,int l)

 {

  // TODO 自動生成的方法存根

  int m=0;

  m=i*j*k*l;//定義一個m變量用來接受乘積值,是一種比較簡單的寫法

  System.out.println(m);

 }

}

/* 調用過程中

 * 實參清單與實參清單的類型一定要保持一緻,拓展還可以寫兩個方法

 */

練習:2./**

 * 設計一個方法,傳入一個int的數組,傳回該數組中最大的值(借鑒Yang_xinqiao的寫法)

 *

 */

public class Demo_02{

 int max=0;

 public void getMax() {

  System.out.println("請輸入數組長度:");

  Scanner sc=new Scanner(System.in);

  int n=sc.nextInt();

  int[] arr=new int[n];

  for(int i=0;i<n;i++) {

   System.out.println("請輸入第"+(i+1)+"個數字:");

   Scanner scanner = new Scanner(System.in);//将得到的數字存入鍵盤

   int num=scanner.nextInt();

   arr[i]=num;

   }

   for(int i=0;i<arr.length;i++) {//數組的周遊

    if(arr[i]>max) {//if語句條件判斷

     max=arr[i];

    }

   }

  System.out.println("該數組的最大值為:"+max);

 }

 public static void main(String[] args) {

  Example11 ex = new Example11();

  ex.getMax();//主方法調用這個構造方法

 }

}

心得體會:感覺Java0基礎學習好難呀,作筆記記錄下來。