编写一个Java程序,使用for循环来逆转一个数组。在这个例子中,for循环从上到下迭代,并将每个值分配给另一个数组。接下来,我们使用另一个for循环来打印这个反向数组。
packege RemainingSimplePrograms;
import java.util.Scanner;
public class Example1 {
private static Scanner sc;
public static void main(String\[\] args) {
int Size, i, j;
sc = new Scanner(System.in);
System.out.print("Enter the size = ");
Size = sc.nextInt();
double\[\] a = new double\[Size\];
double\[\] b = new double\[Size\];
System.out.format("Enter %d elements = ", Size);
for(i = 0; i < Size; i++)
{
a\[i\] = sc.nextDouble();
}
for(i = Size - 1, j = 0; i >= 0; i--, j++)
{
b\[j\] = a\[i\];
}
System.out.println("\\nThe Result");
for(i = 0; i < Size; i++)
{
System.out.print(b\[i\] + " ");
}
}
Enter the size = 4
Enter 4 elements = 22 67 94 122
The Result
122.0 94.0 67.0 22.0
使用while循环反转一个数组的Java程序
package RemainingSimplePrograms;
import java.util.Scanner;
public class Example2 {
private static Scanner sc;
public static void main(String\[\] args) {
int Size, i, j;
double temp;
sc = new Scanner(System.in);
System.out.print("Enter the size = ");
Size = sc.nextInt();
double\[\] a = new double\[Size\];
System.out.format("Enter %d elements = ", Size);
for(i = 0; i < Size; i++)
{
a\[i\] = sc.nextDouble();
}
j = i - 1;
i = 0;
while(i < j)
{
temp = a\[i\];
a\[i\] = a\[j\];
a\[j\] = temp;
i++;
j--;
}
System.out.println("\\nThe Result");
for(i = 0; i < Size; i++)
{
System.out.print(a\[i\] + " ");
}
}
Enter the size = 6
Enter 6 elements = 11 98.4 29.6 12.9 14.4 12.1
The Result
12.1 14.4 12.9 29.6 98.4 11.0
在这个例子中,我们没有使用另一个,而是在一个单一的for循环中反转并打印数组。
package RemainingSimplePrograms;
import java.util.Scanner;
public class ReverseAnArray3 {
private static Scanner sc;
public static void main(String\[\] args) {
int Size, i;
sc = new Scanner(System.in);
System.out.print("Enter the Array size = ");
Size = sc.nextInt();
double\[\] a = new double\[Size\];
System.out.format("Enter %d Array elements = ", Size);
for(i = 0; i < Size; i++)
{
a\[i\] = sc.nextDouble();
}
System.out.println("\\nThe Result of the Reverse Array");
for(i = a.length - 1; i >= 0; i--)
{
System.out.print(a\[i\] + " ");
}
}
使用递归函数反转一个数组的程序。
package RemainingSimplePrograms;
import java.util.Scanner;
public class Example4 {
private static Scanner sc;
public static void main(String\[\] args) {
int Size, i;
sc = new Scanner(System.in);
System.out.print("Enter the size = ");
Size = sc.nextInt();
int\[\] a = new int\[Size\];
System.out.format("Enter %d elements = ", Size);
for(i = 0; i < Size; i++)
{
a\[i\] = sc.nextInt();
}
revArr(a, 0, Size - 1);
System.out.println("\\nThe Result");
for(i = 0; i < Size; i++)
{
System.out.print(a\[i\] + " ");
}
}
public static void revArr(int\[\] a, int start, int end) {
int temp;
if(start < end)
{
temp = a\[start\];
a\[start\] = a\[end\];
a\[end\] = temp;
revArr(a, start + 1, end - 1);
}
}
Enter the size = 8
Enter 8 elements = 12 45 32 44 687 17 122 986
The Result
986 122 17 687 44 32 45 12