Download presentation
Presentation is loading. Please wait.
2
Introduction to Java Programming Lecture 10 Array I Declaring, Creating, and Initializing Arrays
3
What is an Array? F An array is a collection of variables. ( 陣列是一群變數的集合 ) F Arrays have three important properties: – 陣列代表的是一群相關的資料 ( 例如 : 10 個學生的數 學成績, 30 天的股價.) – 同一陣列中的資料有相同的資料型態 (data type) ,同 是 int , double , char … –The size of an array is fixed once it is created. ( 陣列的長度一旦宣告後就固定不能更改了 )
4
Introducing Arrays 陣列是一種資料結構代表一群相同資料型態的資料. An Array of 10 Elements of type double
5
Declaring and Creating Array Variables Syntax datatype[] arrayname; arrayName = new datatype[arraySize]; Example: double[] myList; myList = new double[10]; OR Syntax datatype arrayname[]; arrayName = new datatype[arraySize]; Example: double myList[]; myList = new double[10];
6
Declaring and Creating in One Step Syntax F datatype[] arrayname = new datatype[arraySize]; Example: double[] myList = new double[10]; Syntax F datatype arrayname[] = new dtatype[arraySize]; Example: double myList[] = new double[10];
7
The Length of Arrays F 陣列的長度一旦宣告後就固定不能更改了. 可以使用下列的 方式得到陣列的長度 arrayVariable.length 例如 double myList = new double[10] myList.length // 會 returns 10
8
Initializing Arrays F Using a loop ( 使用迴圈來初始化陣列 ) : for (int i = 0; i < myList.length; i++) myList[i] = i; F Declaring, creating, initializing in one step: ( 同時宣告,建立和初始化陣列 ) double[] myList = {1.9, 2.9, 3.4, 3.5}; ( 必須一次寫完,下面的寫法是錯的 double[] myList; myList = {1.9, 2.9, 3.4, 3.5};)
9
Declaring, creating, initializing Using the Shorthand Notation double[] myList = {1.9, 2.9, 3.4, 3.5}; 這樣就等同於下列的寫法 : double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.