java数组

!!!!!一维数组!!!!

定义一维数组

格式1:数组元素类型     数组名[ ];

格式2:数组元素类型[ ]   数组名;

定义二维数组

格式1:数组元素类型     数组名[ ][ ];

格式2:数组元素类型[ ][ ]   数组名;


元素类型可以是基本类型,也可以是类或接口


用new给一维数组分配空间

数组名 = new 数组元素类型 [元素个数];

       例如, score = new int[10];



用new给二维数组分配空间

数组名 = new 数组元素类型 [元素个数][元素个数];

       例如, score = new int[10][ 8];



定义与分配空间同步进行

int score [ ] = new int[10]; //创建一维数组同时声明


int score [ ][ ]= new int[10][ 8]; //创建二维数组同时声明


数组初始化

一维数组用单层for循环给予赋值,而二维数组则是用二重循环!

数组元素类型 数组名[ ] = {初值表};//一维数组


数组元素类型 数组名[ ][ ] = {初值表}{初值表};//二维数组

查询数组长度

数组名.length


遍历输出数组元素

for(元素类型 循环变量名 : 数组名) {循环体};

for (int a:x) System.out.println(a);//x为数组名


public class lianshou1 {//创建lianshou1类
public static void main(String args[]){//主函数
int[] anArray;//定义数组
anArray = new int[10];//用new给数组分配空间
for(int i = 0;i < anArray.length ; i++){//用for循环给数组元素赋值
anArray[i] = i;
System.out.print(anArray[i]+" ");}//在循环体中输出数组元素
System.out.println();
for(int a:anArray){System.out.println(a);}//遍历输出数组元素
}
}



public class lianshou2 {
public static void main(String[] args){
int [] arrayOfInts = {32,87,3,59,12,106,20,8,62,127};
int searchfor = 12;
int i = 0;
boolean foundIt = false;
for(;i<arrayOfInts.length;i++){
if(arrayOfInts[i] == searchfor){
foundIt = true ;
break;
}
}
if(foundIt){
System.out.println("Found "+searchfor+" at index "+i);
}
else{System.out.println(searchfor+"not in the array");}
}
}


对数组进行由小到大的排序

//方法一:一个固定的开始位置跟所有位置比较。0和123456789比较,1和23456789比较,一次类推。

public class lianshou3 {
public static void main(String[] args){
int a[] = {4,6,3,8,5,3,7,1,9,2};
int n = a.length;
System.out.println("排序前……");
for(int k=0;k<n;k++)
System.out.print(" "+a[k]);
System.out.println();
for(int t=0;t<n-1;t++){
for(int h=t+1;h<n;h++){
if(a[t]>a[h]){
int m=a[t];a[t]=a[h];a[h]=m;
}
}
}

System.out.println("排序后……");
for(int k=0;k<n;k++)
System.out.print(" "+a[k]);
}
}

方法二:Arrays.sort(a);//等价于蓝色字体部分




用new给一维数组分配空间
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值