这里我们解释如何编写 Java 程序来找出数组的反转。首先我们读取数组的限制并读取数组元素。然后使用 `while 循环` 将第一个数组元素放到最后一个位置,第二个元素放到倒数第二个位置,依此类推。然后我们将显示反转后的数组。
`while 循环` 的语法如下所示。
while( condition)
{
// block of code
}
如果条件为真,则代码块会重复执行,直到条件变为假。
首先,我们必须声明类 ArraySum。然后打开主函数。创建一个 Scanner 类的对象。声明一个 Scanner 类的对象。将数组的限制读入变量 n。然后使用 for 循环将数字读入数组 **array[]**。然后使用另一个 for 循环找出数组元素的和 **sum=sum+num**。之后,显示总和。
步骤 1: 声明具有公共修饰符的类 RevArray。
步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始
步骤 3: 初始化一个大小为 100 的整数数组 A[]。
步骤 4: 声明整数变量 l,i,j,temp。
步骤 5: 将数组的限制读入变量 l。
步骤 6: 使用 for 循环将数组元素读入 A[i]。
步骤 7: 设置 j=i-1, i=0。
步骤 8: 使用 `while 循环`,条件为 i < j。
步骤 9: 交换元素 A[i] 和 a[j] 并将 i 增加一。
步骤 10: 重复步骤 8。
步骤 11: 使用 for 循环显示反转后的数组 A[i]。
import java.util.Scanner;
public class RevArray {
public static void main(String args[]) {
int A[] = new int[100];
int l, i, j, temp;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the limit of the array?");
l = scanner.nextInt();
System.out.println("Enter the array elements : ");
for (i = 0; i < l; i++) {
A[i] = scanner.nextInt();
}
j = i - 1;
i = 0;
scanner.close();
while (i < j) {
temp = A[i];
A[i] = A[j];
A[j] = temp;
i++;
j--;
}
System.out.println("Reversed array Elements: ");
for (i = 0; i < l; i++) {
System.out.print(A[i] + " ");
}
}
}
Enter the limit of the array? 5 Enter the array elements : 1 2 3 4 5 Reversed array Elements: 5 4 3 2 1