1、数组的定义
数据类型 数组名[]=new 数据类型[大小]
数据类型 数组名[]={元素值,元素值...}
方法一:
float arry[]=new float[5];
方法二:
int arr[]; //或int[] arr;
arr=new int[5];
方法三:
int a[]={1,1,2,3,5,8,13,21,34,55,89};
2、数组的引用(使用)
数组名[下标]
public static void main(String args[]){ float arr[]={3,6,7.1f,1.1f,3}; float all=0; for(int i=0;i<arr.length;i++){ all+=arr[i]; } System.out.println("平均值"+(all/arr.length)); }
对象数组的使用,综合实例如下:
public class Test { public static void main(String args[]) throws Exception { Dog dogs[] = new Dog[4]; InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); for (int i = 0; i < dogs.length; i++) { dogs[i] = new Dog(); System.out.println("请输入狗名:"); String name = br.readLine(); dogs[i].setName(name); System.out.println("请输入狗的体重:"); String s_weight=br.readLine(); float weight=Float.parseFloat(s_weight); dogs[i].setWeight(weight); } float all_weight=0; for(int i=0;i<dogs.length;i++){ all_weight+=dogs[i].getWeight(); } System.out.println("平均体重:"+(all_weight/dogs.length)); float max_weight=dogs[0].getWeight(); int maxIndex=0; for (int i = 0; i < dogs.length; i++) { if (max_weight<dogs[i].getWeight()){ max_weight=dogs[i].getWeight(); maxIndex=i; } } System.out.println("体重最大的狗是:"+dogs[maxIndex].getName()+"体重是"+dogs[maxIndex].getWeight()); } } class Dog { private String name; private float weight; public String getName() { return name; } public void setName(String name) { this.name = name; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } }
数组小结
1、数组可存放同一类型数据;
2、简单数据类型(int,float)数组,可直接赋值;
3、对象数组在定义后,赋值时需要再次为每个对象分配空间;
4、数组大小必须事先指定;
5、数组名可以理解为执行数组首地址的引用;
6、数组的下标是从0开始编号的。
时间: 2024-12-29 17:42:31