2024年5月7日发(作者:)
数组的定义及使用
数组是一组相关数据的集合,一个数组实际上就是一连串的变量,数组按照使用可以分为一
维数组、二维数组、多维数组;
一维数组
要使用java的数组,必须经过连个步骤:1、声明数组2、为该数组分配内存
* 声明形式一:
声明一维数组:数据类型 数组名[ ]=null;
分配内存给该数组:数组名 =new 数据类型[长度];
* 声明形式二:
声明一维数组(数组的静态初始化):数据类型 数组名[ ]={变量1,变量2,变量3……};
public class ArrayDemo01
{
public static void main(String args[]){
int score[]=null; //声明数组
score=new int[5]; //为数组开辟空间,大小为3
n();
//可以采用数组名[下标]来进行访问
n("score[0] "+score[0]);
n("score[1] "+score[1]);
n("score[2] "+score[2]);
n("score[3] "+score[3]);
//也可以使用for循环来进行访问,得到的效果是一样的
for(int i=0;i<;i++){
n("score["+i+"] "+score[i]);
}
}
}
数组的下标是从0开始的,通过(数组的属性)可以获得当前数组的长度
访问注意:
因为数组的下标是从0开始的,如果索引超出下标的范围,则会抛出
ndexOutOfBoundsException 数组索引越界异常
范例一:判断一组数组中的最大值
public class ArrayDemo02
{
public static void main(String args[]){
int score[]={12,43,1,54,23,89};
int max=0;
//使用静态初始化为数组赋值
//保存数组中的最大值
int min=0; //保存数组中的最小值
max = min =score[0]; //把数组中的第一个元素赋给max和min 目的是为了
取得数组中的最小值 而不是自定义的0
}
}
for(int i=0;i<;i++){ //循环输出
if(score[i]>max){ //依次判断后续元素是否比max大
max=score[i]; //如果大,则赋值给max
//依次判断后续元素是否比min小
//如果小,则赋值给min
}
if(score[i] min=score[i]; } n("数组中的最大值为:"+max); n("数组中的最小值为:"+min); 冒泡排序法:从小到大排列数组中的元素: public class ArrayDemo03 { } public static void main(String args[]){ int score[]={12,43,1,54,23,89}; } int temp=0; for(int i=0;i<;i++){ for(int j=0;j<;j++){ } } if(score[j]>score[i]){ } temp=score[i]; score[i]=score[j]; score[j]=temp; //使用静态初始化为数组赋值 for(int k=0;k<;k++){ n(score[k]); } 二维数组 二维数组的声明方式和一维数组的类似,内存的分配也一样是用new 关键字。其声明与分 配内存的格式如下: ·动态初始化: 1、 数据类型 数组名[ ] [ ]=null;


发布评论