码迷,mamicode.com
首页 > 编程语言 > 详细

Java初步认知和使用一维数组

时间:2018-04-22 12:53:56      阅读:206      评论:0      收藏:0      [点我收藏+]

标签: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初步认知和使用一维数组

标签:java

原文地址:http://blog.51cto.com/13704315/2106390

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!