1、一个数组中有很多个数字,如果想把数组里的数字倒着输出一遍 ,该如何实现呢
1.引入库
代码如下(示例):
package com.array.learn;
/**
* @author 老贝贝
* {@data 2022/11/30}
*/
public class ChangeTest2 {
public static void main(String[] args) {
/**
* 需求:
* 把两个数组中的数字头尾调换顺序
*/
//创建一个数组
int num[] = {100, 200, 300, 400, 500};
//设置容器,两个交换要有一个变量
int temp = 0;
//创造for循环,交换了几次就循环几次
for (int i = 0; i < num.length / 2; i++) {
//将下标赋值给temp,num.length-i-1=下标
temp = num[num.length - i - 1];
//将num中的下标赋值给num[i],也就是说,当num[num.length-i-1]=4时
//也就是i=0,交换下标
num[num.length - i - 1] = num[i];
//把num[i]中的具体数值,具体表现出来,就赋值给temp,
//当num[num.length-i-1]=4时,i=0,
//temp=500
num[i] = temp;
}
//输出交换后的数组,
for (int i = 0; i < num.length; i++) {
System.out.println(num[i]);
}
}
}
本文介绍了如何使用Java实现数组元素的反转。通过创建一个临时变量,在for循环中交换数组首尾元素,达到数组倒序输出的效果。示例代码详细展示了这一过程。
466

被折叠的 条评论
为什么被折叠?



