[JAVA]一维数组的创建, 访问数组元素,遍历数组

 一维数组的创建方法 

     //第一种创建array的方法:
        String[] familyMembers = new String[4];
        familyMembers[0] = "jerry";
        familyMembers[1] = "elaine";
        familyMembers[2] = "george";
        familyMembers[3] = "kramer";


        //第二种创建array的方法:
        String[] familyMembers = new String[]{"jerry", "elaine", "george", "kramer"};

        //第三种创建array的方法:
        String[] familyMembers;
        familyMembers = new String[]{"jerry", "elaine", "george", "kramer"};

        //第四种创建array的方法:
        String[] familyMembers = {"jerry", "elaine", "george", "kramer"}; //初始化必须在同一行

        //下面这种不行
        String[] familyMembers;
        familyMembers = {"jerry", "elaine", "george", "kramer"};

 

访问数组元素,遍历数组

 

public class Array3
{
    public static void main(String[] args)
    {

        String[] familyMembers = {"jerry", "elaine", "george", "kramer"};

        //changing data
        familyMembers[3] = "newman";

        //looping through array
        for (int i = 0; i < familyMembers.length; i++)
        {
            System.out.println(familyMembers[i].toUpperCase());
        }

        // for (String item : familyMembers)
        // {
        //     System.out.println(item);
        // }

    }
}

 

posted @ 2020-05-25 22:45  profesor  阅读(644)  评论(0编辑  收藏  举报