JAVA数组03:数组的三种使用方法

For-Each循环

public static void main(String[] args) {
        // 定义数组并赋值
        int[] array = {1, 3, 5, 7, 9};
        
        // 使用For -Each循环
        for (int arrays : array) {
            System.out.print(arrays + " ");
        }
        // 缺点是无法使用索引读取
   }

数组作方法入参

public static void main(String[] args) {

        // 定义数组并赋值
        int[] array = {1, 3, 5, 7, 9};
        
        TextArray(array); // 将数组入参      
 }

public static void TextArray(int[] array) {

        // 使用for循环遍历数组
        // 这里的i意思是指数组的初始索引
        for(int i = 0;i < array.length;i++){
            System.out.println(array[i]);
     }
}

数组作返回值

public static void main(String[] args) {
    // 定义数组并赋值
    int[] array = {1, 3, 5, 7, 9};
        
    // 接收返回的result数组
    int num = TextArrays(array);
    
    //使用for-each遍历输出
    for(int nums : num){
       System.out.print(nums);
    } 




public static int[] TextArrays(int[] arrays) {
    // 分析,当第一位索引每加1,最后一位索引减1,且互换位置
    // 创建新的数组接收调位,且数组长度为形参数组长度一致
    int[] result = new int[arrays];

    // 使用for循环遍历形参数组,且将形参数组的值赋值给接收数组
    for(int i = 0,j = result.length-1;i <array.length;i++,j-- ){
        
        // 将array数组内每个索引的值转给result数组索引内
        result[j] = array[i];
    }
    // 返回result数组数值
    retrun result;
}

多维数组

  • 多维数组可以看成是数组的数组,语法为:

int[] num = new int[1][2]....;

public static void main(String[] args) {
        // 多维数组

        // 思想为数组内嵌套数组,例: 当有一个数组,数组内还有两个数组
        // 定义一个二维数组 int[][] arrays= new int[1][2];
        int[][] arrays = {{1,2}};// 可以理解为一个花括号为一个数组
        for (int i = 0; i <arrays.length ; i++) {
            // 数组内数组的遍历
            for (int j = 0; j <arrays[i].length ; j++) {
                System.out.println(arrays[i][j]);
            }
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值