1. 程式人生 > >Java初步認知和使用一維數組

Java初步認知和使用一維數組

java

為什麽要使用數組
當你制定的同一類型的變量過多時,我們為了便於操作和管理,所以我們用到數組這個變量。
他其實就是一堆數據有序放置的組合。
什麽是數組
1.數組申明
標識符
數組元素
元素下標
元素類型
元素類型 標識符[元素下標,從0開始]=
{數組元素,數組元素,數組元素(數組長度,當前為3)};


元素類型[元素下標,從0開始] 標識符=
{數組元素,數組元素,數組元素(數組長度,當前為3)};

例1:
int scores[]={1,2,3}; //數組長度3
int[] scores={1,2,3}; //數組長度3
string scores[]={"asd","asd","asd","asd","asd"}; //數組長度5

string[] scores={"asd","asd","asd","asd","asd"}; //數組長度5

例2:
int scores[]=new int[10]; //數組長度10
int[] scores=new int[10]; //數組長度10
String scores[]=new String[20]; //數組長度20
String[] scores=new String[20]; //數組長度20

註意1:同一數組只能使用例1和例2申明的其中一種。
例如int scores[]={1,2,3}; int scores[]=new int[10];這樣是錯誤的。

註意2:在申明的時候數組長度和數組元只能寫一種。
例如int scores[3]={1,2,3}; int scores[]=new int[3] ={1,2,3};這樣是錯誤的。

2.數組賦值
給數組賦值時必須寫清楚數組的下標。
例如
int scores[]=new int[10];
scores[0]=5;
scores[1]=5;
scores[0]= scores[0]*5;
System.out.println(scores[0]+"\t"+ scores[1]);

結果是:25 5

常見的運用
用for循環加上鍵盤賦值運算
scanner input=new Scanner(System.in);

int scores[]=new scores[10];
int num=0;
for(int i=0;i< scores.length;i++){ //循環10次賦值
scores[i]=input.nextint(); //用鍵盤賦值
num+= scores[i]; //求數組數據之和
}
技巧1:scores.length等於數組的長度可直接用來確定循環次數。

用強化for循環
scanner input=new Scanner(System.in);
int scores[]=new scores[10];
int num=0;
for(int score:scores){ //循環10次賦值
num+= score; //求數組數據之和
}
技巧:for(int score:scores)數組專用的強化for語句,表示每一次循環都會把數組scores的值從下標"0"開始,賦值給score。

常見的錯誤
1.只要是申明與賦值和數組長度一起寫的時候,賦值和數組長度必須寫一個。
int scores=new scores[]; (錯誤)
int scores=new scores[1]; (正確)
int scores=new scores[]{1,2,3}; (正確)

2.數組越界
int scores=new scores[2];
scores[0]=1;
scores[1]=1;
scores[2]=1;
scores[3]=1;
分析:數組之申明了兩個數據,所以不應該出現scores[2] 和scores[3],這屬於數組越界。

3語法規定,申明和數組一次性全部賦值必須一條語句完成
int scores[];
scores={1,2,3}; (錯誤)

int scores[]={1,2,3}; (正確)

Java初步認知和使用一維數組