JAVA——实现数组元素逆序遍历输出
题目:假设有一个长度为5的数组,数组元素通过键盘录入,如下所示:int[] arr = {1,3,-1,5,-2}要求:创建一个新数组newArr[],新数组中元素的存放顺序与原数组中的元素逆序,并且如果原数组中的元素值小于0,在新数组中按0存储。最后输出原数组和新数组中的内容打印格式:请输入5个整数:1...
·
题目:
假设有一个长度为5的数组,数组元素通过键盘录入,如下所示:
int[] arr = {1,3,-1,5,-2}
要求:
创建一个新数组newArr[],新数组中元素的存放顺序与原数组中的元素逆序,并且如果原数组中的元素值小于0,
在新数组中按0存储。最后输出原数组和新数组中的内容
打印格式:
请输入5个整数:
1
3
-1
5
-2
原数组内容:
1 3 -1 5 -2
新数组内容:
0 5 0 3 1
代码如下:
public class Test6 {
public static void main(String[] args) {
// 定义原数组
int[] arr = new int[5];
Scanner sc = new Scanner(System.in);
// 采用键盘录入给数组的每一个元素赋值
System.out.println("请输入5个整数:");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
System.out.println("原数组内容:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
// arr : 1 3 -1 5 -2
// 定义新数组
int[] newArr = new int[arr.length];
// 模拟新数组的索引
int index = 0;// index = 3
for (int i = arr.length - 1; i >= 0; i--) {// i = 1
if (arr[i] < 0) {
newArr[index] = 0;
} else {
newArr[index] = arr[i];
}
index++;
}
System.out.println("新数组内容:");
for (int i = 0; i < newArr.length; i++) {
System.out.print(newArr[i] + " ");
}
}
}
输出结果如下:
请输入5个整数:
5
3
7
9
5
原数组内容:
5 3 7 9 5
新数组内容:
5 9 7 3 5
更多推荐
所有评论(0)