Java基础系列 - 数组、二维数组、对象数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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;
    }
}

  

posted @   深南大道  阅读(538)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示