一维数组
一维数组必须先声明后才能使用,声名方式有两种:
- 数组元素类型[] 数组名;例如 int[] a;
- 数组元素类型 数组名[];例如 int a[];
声明数组结束,如接下来要真正使用数组,还要给数组分配存储空间,即创建数组。在创建数组的时候必须指明数组的长度,即数组中可存储的数据的个数,创建的语法格式为:
- 数组名 = new 数组元素类型[数组长度];例如 a=new int[20];
也可以把声明和创建的过程合在一起完成:
- int[] a=new int[20];
创建之后,系统会给每个数组自动分配初始值,注意数组一旦被创建,大小就无法再改变;
在定义数组的同时,也可以自己对数组进行初始化,例如:
- int[] a={9,12,-1,3,6};
- 或者int[] a=new int[]{9,12,-1,3,6};
用花括号进行初始化的时候,前面的方括号里不能制定数组大小,否则会报错:Cannot define dimension expressions when an array initializer is provided,即:在提供数组初始化时不能定义维度表达式.
对于声明并创建好的数组进行访问,需要通过数组的下标例如a[0]=3;下标也可以是整数表达式,不一定是一个简单的下标数字,java数组元素下标是从0开始的,这点和C,C++都是一样的;
java中可以用如下形式的表达式来获得数组的长度也就是数组里所含的元素个数:
数组名.length
例如如果有int[] a=new int[20];那么a.length 的值就是20;
下面是一个定义数组和访问数组的例子:
public static void intarray1()
{
Scanner kb=new Scanner(System.in);
int[] score=new int[10];
double sum=0;
System.out.printf("enter 10 intergers and calculate the average with functionOne\n", sum);
for(int i=0;i<score.length;++i)
{
score[i]=kb.nextInt();
sum+=score[i];
}
System.out.printf("the average of them is %.2f\n", sum/score.length);
}//数组的定义和初始化的例子,用for循环和下标来控制数组操作
运行结果如下:
Java中foreach语句的使用,foreach语句可以通过for循环来实现遍历数组中的每一项,语法定义格式如下:
- for(元素类型 元素变量:遍历对象)
- {引用了元素变量的语句;}
对上面相同例子里的操作换成用foreach语句如下:
public static void intarray2()
{
Scanner kb=new Scanner(System.in);
int[] score=new int[10];
double sum=0;
System.out.printf("enter 10 intergers and calculate the average with functionTwo\n", sum);
for(int i=0;i<score.length;++i)
{
score[i]=kb.nextInt();
}
for(int x:score)//foreach语句的写法遍历在数组score里的每一个int变量x
{
sum+=x;
}
System.out.printf("the average of them is %.2f\n", sum/score.length);
}//用foreach语句达到一样的效果
运行结果如下: