Java 07

来源:互联网 发布:谷歌浏览器调试js 编辑:程序博客网 时间:2024/06/05 03:46

数组01
数组是一组相关数据的集合,可以分为一维数组,二维数组和多维数组。
一维数组存放的数据类型必须是相同的。
使用java数组的时候必须要声明数组和分配内存给数组。
数据类型 数组名[] = null; //声明一维数组
数组名=new 数据类型[长度];//分配内存给数组
例子:
int score[] = null;
score = new int[3];
也可以用简单的方式
数据类型 数组名[] = new 数据类型[个数]
int score[] = new int[3];
若想要访问数组中的元素可以用索引来完成,编号由0开始。
public class Demo{
public static void main(String[] args){
int score[] = null;
score = new int[3];
for(int x = 0; x < 3; x++)
System.out.println(score[x]);
}
}
结果为
0
0
0
若要为数组中的元素赋值
public class Demo{
public static void main(String[] args){
int score[] = null;
score = new int[3];
for(int x = 0; x < 3; x++){
score[x]=x;
System.out.println(score[x]);
}
}
}
结果为
0
1
2
在java中取得的数组长度可以用数组名称.length,如
public class Demo{
public static void main(String[] args){
int score[] = null;
score = new int[3];
System.out.println(score.length);
}
}
结果为3
数组也可以再声明的时候直接赋初值,如
public class Demo{
public static void main(String[] args){
int score[] = {1,2,3,4,5};
for(int x = 0; x < 5; x++)
System.out.println("score[" + x + "] = " + score[x]);
System.out.println("长度为" + score.length);
}
}
结果为
score[0] = 1
score[1] = 2
score[2] = 3
score[3] = 4
score[4] = 5
长度为5

0 0
原创粉丝点击