Java中的数组: 用来存放一系列数据类型相同的元素(数据的类型需要一样) 数组是一种引用数据类型
数组定义的格式:
-
数据类型[] 数组名=new 数据类型[数据长度]; -
数据类型[] 数组名={值1,值2,值3,-----,值n}:知道数组里面存放什么数据 -
数据类型[] 数组名=new 数据类型[]{值1,值2,值3,-----,值n}; 打印数组:Arrays.toString(数组名) 注意 1.直接输出数组名会输出数组在内存中的地址,如果需要输入数组中的内容,需要通过Arrays.toString(数组变量名) 2.如果定义数组没有手动存放数据,数组会默认存放,对应数据类型的默认值 int 默认值 0 boolean 默认值是false double默认值是0.0 String(引用数据类型)默认值都是null 3.数组定义时,必须指定长度 ` 获取数组的长度:数组名.length 获取数组中的元素格式: 数组名[数组下标] 数组下标是从0开始的,到 (数组名.length-1)
public static void main(String[] args) {
int [] a=new int[3];
System.out.println(Arrays.toString(a));
String[] b= {"1","2","3","4"};
System.out.println(Arrays.toString(b));
String[] c=new String[] {"1","2","3","4"};
System.out.println(Arrays.toString(c));
int f=c.length;
System.out.println(f);
System.out.println(c[2]);
System.out.println(c[c.length-1]);
c[1]="e";
System.out.println(Arrays.toString(c));
String ns=Arrays.toString(c);
System.out.println(ns);
for (int i = 0; i < c.length; i++) {
System.out.println("第"+(i+1)+"循环:"+c[i]);
}
int [] number=new int[5];
System.out.println(Arrays.toString(number));
for (int i = 0; i < number.length; i++) {
number[i]=i*10;
}
System.out.println(Arrays.toString(number));
}
小作业: 统计5名同学的考试成绩:
- 计算出总成绩
- 计算出平均成绩
- 计算出班级最低分
- 计算出班级最高分
爆错出现:ArrayIndexOutOfBoundsException 表示:数组下标越界
public static void main(String[] args) {
double sum=0;
double min=0;
double max=0;
double average=0;
double [] grades=new double[5];
Scanner key=new Scanner(System.in);
for (int i = 0; i < grades.length; i++) {
System.out.println("请输入"+(i+1)+"名同学的考试成绩!");
grades[i]=key.nextDouble();
}
System.out.println("成绩表 :"+Arrays.toString(grades));
min=grades[0];
max=grades[0];
for (int i = 0; i < grades.length; i++) {
sum=sum+grades[i];
if(min>grades[i]) {
min=grades[i];
}
if(max<grades[i]) {
max=grades[i];
}
}
average=sum/5.0;
System.out.println("总成绩:"+sum+"\t最低成绩"+min+"\t最高成绩:"+max+"\t平均成绩:"+average);
key.close();
}
英雄大战
public static void main(String[] args) {
String name1="one";
int blood1=500;
String[] sk1= {"q","w","e","r"};
int [] skhrt= {70,80,100,150};
String name2="two";
int blood2=600;
String[] sk2= {"q","w","e","r"};
int [] skhrt2= {50,60,80,100};
Random rd=new Random();
while (true) {
int index1=rd.nextInt(sk1.length);
String s1=sk1[index1];
int hr1=skhrt[index1];
if (blood2>0) {
blood2-=hr1;
if (blood2<=0) {
blood2=0;
}
}
System.out.println(name1+"对"+name2+"释放"+s1+"造成"+hr1+"伤害,敌方还剩余:"+blood2+"血量");
if(blood2==0) {
System.out.println(name1+"打败"+name2+","+name1+"获胜");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int index2=rd.nextInt(sk2.length);
String s2=sk2[index2];
int hr2=skhrt2[index2];
if (blood1>0) {
blood1-=hr2;
if (blood1<=0) {
blood1=0;
}
}
System.out.println(name2+"对"+name1+"释放"+s2+"造成"+hr2+"伤害,敌方还剩余:"+blood1+"血量");
if(blood1==0) {
System.out.println(name2+"打败"+name1+","+name1+"获胜");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|