package com.test2;
public class demo2 {
public static void main(String[] args) {
/**
* 一维数组使用
*/
//数组最大的缺陷:长度固定
//int data[] = {10, 20, 30}; /*开辟了一个长度为3的数组*/
//int[] arr3 = new int[]{1, 2, 3, 4, 5, 6, 7, 22};
int[] data = new int[3];
data[0] = 10;
data[1] = 20;
data[2] = 30;
for (int x = 0; x < data.length; x++) {
System.out.println(data[x]); //通过循环控制索引
}
System.out.println("------------------------------------");
/**
* 二维数组
*/
//此时的数组并不是一个等列数组
int data2[][] = new int[][]{
{1, 2, 3}, {4, 5}, {6, 7, 8, 9}};
//如果在进行输出的时候一定要使用双重循环,
//外部的循环控制输出的行数,而内部的循环控制输出列数
for (int i = 0; i < data2.length; i++) {
for (int j = 0; j < data2[i].length; j++) {
System.out.print("data[" + i + "][" + j + "]=" + data2[i][j] + "、");
}
System.out.println();
}
/* 显示
data[0][0]=1、data[0][1]=2、data[0][2]=3、
data[1][0]=4、data[1][1]=5、
data[2][0]=6、data[2][1]=7、data[2][2]=8、data[2][3]=9、
* */
/**
* 对象数组
*/
Dog[] dogs = new Dog[4];
Dog dog1 = new Dog("花花", 100f);
Dog dog2 = new Dog("绿绿", 101f);
Dog dog3 = new Dog("红红", 102f);
Dog dog4 = new Dog("白白", 103f);
dogs[0] = dog1;
dogs[1] = dog2;
dogs[2] = dog3;
dogs[3] = dog4;
for (int i = 0; i < dogs.length; i++) {
System.out.println();
System.out.printf("名字:%s 体重:%s", dogs[i].getName(), dogs[i].getWeight());
}
/* 显示
名字:花花 体重:100.0
名字:绿绿 体重:101.0
名字:红红 体重:102.0
名字:白白 体重:103.0
* */
}
}
class Dog {
private String Name;
private float weight;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public Dog(String name, float weight) {
Name = name;
this.weight = weight;
}
}