Java数组

定义

  • 数组是相同数据类型的数据按顺序组成的一种引用数据类型。

声明数组

  • 声明一维数组:数组元素数据类型 [ ] 数组名;

    String [] countryArray;
    
  • 声明二维数组:数组元素数据类型[ ][ ] 数组名;

    String [] [] account;
    

实例化数组

  • 声明数组仅仅给出了元素的数据类型和数组名字,要使用数组就必须为它分配内存空间,即实例化数组。当实例化一个数组时就申请了一段连续的内存空间存储数组中的元素。实例化数组的方法有两种:

    1. 指定长度

      double [] score = new double[3];
      String [] [] account = new String [3] [2];
      
    2. 穷举法

      double [] score_1 = {59,78.5,33};//声明的同时实例化
      double [] score_2 = new double[]{59,78.5,33};//声明的同时实例化
      double [] score_3;
      score_3 = new double[] {33.6,99,73.2};//先声明后实例化
      //score_3 = {33.6,99,73.2};不可以
      String [] [] account_1 = {{"小明","123456"},{"小华","111111"},{"小军","222222"}};
      String [] [] account_2 = new String [] [] {{"小明","123456"},{"小华","111111"},{"小军","222222"}};
      

操作数组元素

  • 数组中的数据通过数组名和数组下标来操作数据,下标从0开始:

    double [] scores = new double [3];
    //如何给数组元素赋值
    scores[0] = 9.0;
    scores[1] = 8.2;
    scores[2] = 7.8;
    //如何获取数组元素
    System.out.println(scores[2]);
    

for遍历数组元素

  • 传统for循环

    1. 一维数组

      double [] scores = new double [3];
      scores[0] = 9.0;
      scores[1] = 8.2;
      scores[2] = 7.8;
      for(int i=0;i<3;i++)
          System.out.println(scores[i]);
      
    2. 二维数组

      String [] [] account_1 = {{"小明","123456"},{"小华","111111"},{"小军","222222"}};
      for(int i=0;i<account_1.length;i++) {
      String [] account = account_1[i];
      for(int j=0;j<account.length;j++) {
          System.out.print(account[j]+"\t");
      }
      System.out.println();
      
  • 增强for循环

    1. 一维数组

      double [] scores = new double [3];
      scores[0] = 9.0;
      scores[1] = 8.2;
      scores[2] = 7.8;
      for(double score:scores)
          System.out.println(score);
      
    2. 二维数组

      String [] [] account_2 = {{"小明","123456"},{"小华","111111"},{"小军","222222"}};
      for(String [] account:account_2) {
          for(String s:account) {
              System.out.print(s+"\t");
          }
          System.out.println();
      }
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值