java,定义一个整数数组,123456要求置换数组。遍历元数组,把数组的值用逗号隔开,打印在同一行,把数组内的数进行倒序重放
时间: 2023-05-30 12:03:46 浏览: 85
以下是Java代码:
```
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6};
int temp;
int len = array.length;
for (int i = 0; i < len / 2; i++) { // 倒序重放
temp = array[i];
array[i] = array[len - i - 1];
array[len - i - 1] = temp;
}
for (int i = 0; i < len; i++) { // 打印数组
System.out.print(array[i]);
if (i != len - 1) {
System.out.print(",");
}
}
}
}
```
输出为:6,5,4,3,2,1
相关问题
定义一个整数数组,123456要求置换数组。遍历元数组,把数组的值用逗号隔开,打印在同一行,把数组内的数进行倒序重放
以下是Python的代码实现:
```python
nums = [1, 2, 3, 4, 5, 6]
print("原数组:", end=" ")
for num in nums:
print(num, end=", ")
print()
# 数组倒序重放
nums = nums[::-1]
print("倒序数组:", end=" ")
for num in nums:
print(num, end=", ")
```
输出结果为:
```
原数组: 1, 2, 3, 4, 5, 6,
倒序数组: 6, 5, 4, 3, 2, 1,
```
其中,`nums[::-1]`表示将列表nums的元素倒序排列。
java,定义两个容纳六个数的整数数组,遍历原数组,把数组的值用空格隔开,打印在同一行,实现两个数组的内容交换。遍历打印置换后的数组值
```java
public class ArraySwap {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5, 6};
int[] arr2 = {7, 8, 9, 10, 11, 12};
System.out.print("arr1: ");
printArray(arr1);
System.out.print("\narr2: ");
printArray(arr2);
// swap arrays
int[] temp = arr1;
arr1 = arr2;
arr2 = temp;
System.out.print("\narr1: ");
printArray(arr1);
System.out.print("\narr2: ");
printArray(arr2);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
输出结果:
```
arr1: 1 2 3 4 5 6
arr2: 7 8 9 10 11 12
arr1: 7 8 9 10 11 12
arr2: 1 2 3 4 5 6
```
阅读全文