Java | 一维数组的遍历

一、使用for循环遍历数组

在Java中,使用for循环是遍历数组的一种常见方式。通过数组的索引来访问每个元素,直到遍历完数组的所有元素。

demo:

public class ForLoopTraversal {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        // 使用for循环遍历数组
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");
        }
        // 输出:1 2 3 4 5
    }
}

二、使用增强for循环遍历数组

Java提供了增强的for循环(也称为"for-each"循环),它简化了数组的遍历。这种循环不需要使用索引来访问数组元素,而是直接遍历数组中的每个元素。

demo:

public class EnhancedForLoopTraversal {
    public static void main(String[] args) {
        String[] names = {"Alice", "Bob", "Charlie"};
        // 使用增强for循环遍历数组
        for (String name : names) {
            System.out.print(name + " ");
        }
        // 输出:Alice Bob Charlie
    }
}

三、使用while循环遍历数组

虽然不常见,但也可以使用while循环来遍历数组。需要维护一个索引变量,并在每次迭代后更新它。

demo:

public class WhileLoopTraversal {
    public static void main(String[] args) {
        double[] decimals = {1.1, 2.2, 3.3, 4.4, 5.5};
        // 使用while循环遍历数组
        int index = 0;
        while (index < decimals.length) {
            System.out.print(decimals[index] + " ");
            index++;
        }
        // 输出:1.1 2.2 3.3 4.4 5.5
    }
}

四、使用do-while循环遍历数组

do-while循环也可以用于遍历数组。与while循环不同,do-while循环至少执行一次循环体,即使数组为空。

demo:

public class DoWhileLoopTraversal {
    public static void main(String[] args) {
        char[] letters = {'A', 'B', 'C', 'D', 'E'};
        // 使用do-while循环遍历数组
        int index = 0;
        do {
            System.out.print(letters[index] + " ");
            index++;
        } while (index < letters.length);
        // 输出:A B C D E
    }
}

五、数组的反向遍历

有时需要从数组的最后一个元素开始遍历到第一个元素。可以通过从length - 1开始递减索引来实现。

demo:

public class ReverseTraversal {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        // 反向遍历数组
        for (int i = numbers.length - 1; i >= 0; i--) {
            System.out.print(numbers[i] + " ");
        }
        // 输出:5 4 3 2 1
    }
}

以上就是本次分享的所有内容,感兴趣的朋友点个关注呀,感谢大家啦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值