1. 程式人生 > >Java 基本語法----數組

Java 基本語法----數組

運行 back for test 聲明數組 class 學員 變量 tro

數組

數組概述

數組是多個相同類型數據的組合,實現對這些數據的統一管理。
數組屬引用類型,數組型數據是對象(Object),數組中的每個元素相當於該對象的成員變量。
數組中的元素可以是任何數據類型,包括基本類型和引用類型。


一維數組聲明

一維數組的聲明方式: type var[] 或 type[] var
例如:
  int a[];
  int[] a1;
  double b[];
  Mydate []c; //對象數組
Java語言中聲明數組時不能指定其長度(數組中元素的數), 例如: int a[5]; //非法


數組元素的引用

Java中使用關鍵字 new 創建數組對象


定義並用運算符 new 為之分配空間後,才可以引用數組中的每個元素;
數組元素的引用方式:數組名[數組元素下標]
  數組元素下標可以是整型常量或整型表達式。如a[3] , b[i] , c[6*i];
  數組元素下標從0開始;長度為n的數組合法下標取值範圍: 0 - n-1;

  如int a[]=new int[3]; 可引用的數組元素為a[0]、a[1]、a[2]
每個數組都有一個屬性 length 指明它的長度,例如:a.length 指明數組 a 的長度(元素個數)


數組元素的默認初始化

數組是引用類型,它的元素相當於類的成員變量,因此數組一經分配空間,其中的每個元素也被按照成員變量同樣的方式被隱式初始化


例如:
public class Test {
  public static void main(String argv[]) {
    int a[]= new int[5];
    System.out.println(a[3]); //a[3]的默認值為0
  }
}


數組元素的默認初始值

技術分享


創建基本數據類型數組

Java中使用關鍵字new 創建數組對象

public class Test {
 public static void main(String args[]) {
  int[] s;
  s = new int[10];
  for ( int i=0; i<10; i++ ) {
   s[i] 
=2*i+1;    System.out.println(s[i]);   }  } }


創建對象數組

1、

class MyDate{
    private int day;
    private int month;
    private int year;
    public MyDate(int d, int m, int y){
        day = d; month = m; year = y;
    }
    public void display(){
        System.out.println(day + "-" + month + "-" + year);
    }
}


2、

public class Test {
    public static void main(String args[]) {
        MyDate[] m;
        m = new MyDate[10];
        for ( int i=0; i<10; i++ ) {
            m[i] =new MyDate(i+1, i+1,1990+i);
            m[i].display();
        }
    }
}


數組初始化

動態初始化:數組定義與為數組元素分配空間並賦值的操作分開進行。

    int a[];
    a = new int[3];
    a[0] = 3;
    a[1] = 9;
    a[2] = 8;
    MyDate dates[];
    dates = new MyDate[3];
    dates[0] = new MyDate(22, 7, 1964);
    dates[1] = new MyDate(1, 1, 2000);
    dates[2] = new MyDate(22, 12, 1964);


靜態初始化:在定義數組的同時就為數組元素分配空間並賦值。

    int a[] = { 3, 9, 8};

    MyDate dates[] = {
        new MyDate(22, 7, 1964),
        new MyDate(1, 1, 2000),
        new MyDate(22, 12, 1964)
    };


練習


1、數組的常見操作

    //1. 數組的聲明
    //int    i = 0;
    int [] a = null; //推薦使用此種方式進行聲明. 
    int b [] = null;
        
    //註意: Java語言中聲明數組時不能指定其長度(數組中元素的數)
    //int [5] c = null;
        
    //註意: 若沒有為數組變量分配指向的內存空間, 就調用其屬性, 會在運行時發生 "空指針異常"
    //System.out.println(a.length); 
        
    //2. 為數組分配內存空間
    a = new int[10];

    //3. 獲取數組的長度
    System.out.println(a.length);  //10
        
    //5. 對數組元素進行初始化
    for(int i = 0; i < a.length; i++){
        a[i] = 100 + i;
    }
        
    //4. 訪問數組的元素: 數組名[數組元素下標]. 註意: 下標從 0 開始, 所以最大值是 lengh - 1, 而不是length;
    //數組元素會進行默認的初始化: 
    for(int i = 0; i < a.length; i++){
        System.out.println(a[i]);
    }
        
    //若訪問數組的下標超過合法範圍, 則在運行時會拋出ArrayIndexOutOfBoundsException
    //a[10] = 10;
        
    //數組的靜態初始化
    int [] c = {1, 2, 3, 4, 5};
    int [] d = new int[]{2, 3, 4, 5, 6};
        
    for(int i = 0; i < d.length; i++){
        System.out.println(d[i]);
    }
        
    //聲明一個二維數組
    int [][] aa = new int[5][];
        
    //對二維數組的元素進行初始化: 二維數組的元素是一個一維數組!
    //遍歷需要使用嵌套的 for 循環. 
    for(int i = 0; i < aa.length; i++){
        aa[i] = new int[i + 1];
            
        for(int j = 0; j < aa[i].length; j++){
            aa[i][j] = 1 + i * j;
        }
    }
        
    //對二維數組進行遍歷
    for(int i = 0; i < aa.length; i++){
        for(int j = 0; j < aa[i].length; j++){
            System.out.print(aa[i][j] + "  ");
        }
        System.out.println(); 
    }


2、從鍵盤讀入學生成績,找出最高分,並輸出學生成績等級。
  成績>=最高分-10 等級為’A’ 成績>=最高分-20 等級為’B’
  成績>=最高分-30 等級為’C’ 其余 等級為’D’
  提示:先讀入學生人數,根據人數創建int數組,存放學生成績。

  /**
   * 2.從鍵盤讀入學生成績,找出最高分,並輸出學生成績等級。
   *        成績>=最高分-10  等級為’A’   成績>=最高分-20  等級為’B’
   *         成績>=最高分-30  等級為’C’   其余     等級為’D’
   *   提示:先讀入學生人數,根據人數創建int數組,存放學生成績。
   */
    //1. 創建 Scanner 類
    Scanner scanner = new Scanner(System.in);
        
    //2. 讀入要錄入的學生人數
    System.out.print("請輸入學生人數");
    int count = scanner.nextInt();
    
    //3. 創建一個 int 類型的數組, 用於存放學員的成績, 數組的長度為 2 所錄入數值
    int [] scores = new int[count];
        
    //4. 利用循環錄入學生的成績, 同時得到最高分. 把學生成績錄入到 3 聲明的數組中.
    int highScore = 0;
        
    for(int i = 0; i < scores.length; i++){
        scores[i] = scanner.nextInt();
    
        if(scores[i] > highScore){
            highScore = scores[i];
        }
    }
        
    //5. 遍歷 3 聲明的數組, 根據最高分, 獲取學生的升級等級. 
    for(int i = 0; i < scores.length; i++){
        if(scores[i] >= highScore - 10){
            System.out.println("student " + i + " score is " + scores[i] + "  grade is A");
        }else if(scores[i] >= highScore - 20){
            System.out.println("student " + i + " score is " + scores[i] + "  grade is B");
        }else if(scores[i] >= highScore - 30){
            System.out.println("student " + i + " score is " + scores[i] + "  grade is C");
        }else{
            System.out.println("student " + i + " score is " + scores[i] + "  grade is D");
        }
    }

多維數組

二維數組舉例:
int [][] a = {{1,2},{3,4,0,9},{5,6,7}};

技術分享


Java中多維數組被做為數組的數組處理
Java中多維數組的聲明和初始化應按從高維到低維的順序進行
  int t [][] = new int [4][];//t有4行,第一個維數不空即可
  t[0] = new int[5]; //每一行都是一個有5個元素的一維數組
  t[1] = new int[5];
  int t1[][] = new int [][4]; //非法


Java中多維數組不必須是規則矩陣形式
  int[][] tt = new int[4][];
  tt[0] = new int[2];
  tt[1] = new int[4];
  tt[2] = new int[6];
  tt[3] = new int[8];

  int tt[][] = new int[4][5]; //tt是一個4行5列的二維數組

  int [][] aa = new int[4][];

  aa[0] = new int[5];

  aa[1] = new int[1];

  aa[2] = new int[3];

  //…

技術分享


多維數組初始化

靜態初始化
  int intArray[][] = {{1,2},{2,3},{3,4,5}};
  int intArray1[3][2] = {{1,2},{2,3},{4,5}};
  //illegal,等號左邊不能指定維數
動態初始化
  int a[][] = new int[4][5];
  int b[][] = new int[3][]
  b[0] = new int[2];
  b[1] = new int[3];
  b[2] = new int[5];


數組排序

Java.util.Arrays類的 sort() 方法提供了數組元素排序功能:

 1 import java.util.*;
 2 public class Sort {
 3     public static void main(String[] args) {
 4         int [] number = {5,900,1,5,77,30,64,700};
 5         Arrays.sort(number);
 6 
 7         for(int i = 0; i < number.length; i++)
 8             System.out.println(number[i]);
 9     }
10 }

使用二維數組打印 10 行的楊輝三角, 楊輝三角實際上是二項式展開式的系數

/**
  * 1                       (a+b)^0
  * 1  1                    (a+b)^1
  * 1  2  1                 (a+b)^2
  * 1  3  3  1              (a+b)^3 
  * 1  4  6  4  1
  * 1  5  10 10 5  1
  * ...
  * 1. 什麽是楊輝三角: 二項式展開式的系數
  * 2. 為什麽使用的是 二維數組: 因為楊輝三角由行和列組成, 每一行是一個一維數組, 而楊輝三角則是有一維數組組成的數組, 即二維數組. 
  * 3. 楊輝三角的具體特點: 
  * 3.1 第 n 行有 n 個元素(n >= 1)
  * 3.2 每一行的第一個元素和最後一個元素都是 1
  * 3.3 不等於 1 的那些元素的值為上一行的對應列和對應列的前一列的元素的和. 
*/
        
    //1. 先聲明一個二維數組: 二維數組有 10 個元素
    int [][] yh = new int[10][];
        
    //2. 對二維數組的元素進行初始化: 第 i 個元素(i 從 0 開始) 為長度為 i + 1 的一維數組.
    for(int i = 0; i < yh.length; i++){
      //二維數組的每一個元素是一維數組, 而一維數組時引用類型, 其默認值為 null
      //System.out.println(yh[i]); 
            
      yh[i] = new int[i + 1];

      //3. 對具體的每一個元素進行初始化(是 1 的元素): yh[i][0] = 1, yh[i][i] = 1
      yh[i][0] = 1;
      yh[i][i] = 1;

      //4. 對具體的每一個元素進行初始化(不是 1 的元素): yh[i][j] = yh[i-1][j] + yh[i-1][j-1]; 
      //   (i > 1 && j > 0 && j < i)
      if(i > 1){
          for(int j = 1; j < i; j++){
              yh[i][j] = yh[i-1][j] + yh[i-1][j-1];
          }
      }
    }
    //打印
    for(int i = 0; i < yh.length; i++){
        for(int j = 0; j < yh[i].length; j++){
            System.out.print(yh[i][j] + "\t");
        }
       System.out.println();
  }

Java 基本語法----數組