JAVA数组的简单使用
import java.util.Arrays;
public class Arrary1011 {//定义静态类
public static void main(String[] args){//公共静态主函数
int[]ages;//定义整型参数
ages=new int[]{18,17,19,18,19};//创建整型数组[]可在数组名称后也可在数组类型后,一般在数组类型之后
double[]weight = {55.3,66.5,77.3,45.1};//创建双精度浮点型数组
float tall[]={172,173,175,180};//创建浮点型数组
double[][]ClassTall={
{172,173},
{},
{175,180,185,169,177},
{163},
null
};//创建二维浮点型数组对应班级和身高二维
String[] names ={"tom","jian","yang","jim","green"};//创建字符串数组
int i=0;//int i;定义初始化临时变量,初始值默认为0
for (;i<names.length;i++){//for (i=0;i<names.length;i++);不同的循环结构打印数组
System.out.printf("%s: %d\n",names[i],ages[i]);//打印数组,每打印一次则空行
}
/*
int i=0;
for (;;){//for (;;)<===>while(true);//(;;)参照(;i<names.length;i++),有缺省
System.out.printf("%s: %d\n",names[i],ages[i]);
i++;
if(i>names.length){
break;//循环结束则跳出
}
}
*/
/*HashMap<String,Integer> ageMap=new HashMap<>();//字典查询时不可用intHashMap<String,Int>ageMap={"tom":18};
ageMap.put("tom",18);
ageMap.put("jian",17);
ageMap.put("yang",19);
ageMap.put("jim",18);
ageMap.put("green",19);
ageMap.forEach(k,v)->System.out.printf("%s:%d/n",k,v));// 此处采用查询遍历取代for循环,当关键字重复时,取后者关键字对应的值
*/
System.out.println("ages[0]="+ages[0]);//打印一维数组元素ages[0]
System.out.println("weight[3]="+weight[3]);//打印一维数组元素weight[3]
System.out.println("agesLength="+ages.length);//打印一维数组长度agesLength
System.out.println("tall[0]="+tall[0]);//打印一维数组元素tall[0]
System.out.println("ClassTall[0]="+ClassTall[0]);//打印二维数组中的一行,输出乱码
System.out.println("ClassTall[1]="+ClassTall[1]);//打印二维数组中的一行,输出乱码
System.out.println("ClassTall[2][3]="+ClassTall[2][3]);//打印二维数组元素ClassTall[2][3]
System.out.println("ClassTall[4]="+ClassTall[4]);//打印出值为空
System.out.println("=ClassTall[1]length="+ClassTall[0].length);//打印一年级人数
System.out.println("=ClassTall[2]length="+ClassTall[1].length);//打印二年级人数
System.out.println("=ClassTall[3]length="+ClassTall[2].length);//打印三年级人数
System.out.println("=ClassTall[4]length="+ClassTall[3].length);//印四年级人数
System.out.println("ClassTall[][]="+Arrays.toString(ClassTall));//打印二维数组,输出乱码
}
}
运行结果:
tom: 18
jian: 17
yang: 19
jim: 18
green: 19
ages[0]=18
weight[3]=45.1
agesLength=5
tall[0]=172.0
ClassTall[0]=[D@26d4f1
ClassTall[1]=[D@1662dc8
ClassTall[2][3]=169.0
ClassTall[4]=null
=ClassTall[1]length=2
=ClassTall[2]length=0
=ClassTall[3]length=5
=ClassTall[4]length=1
ClassTall[][]=[[D@26d4f1, [D@1662dc8, [D@147c5fc, [D@1174b07, null]