多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Java 程序:反转数组 > 原文: [https://beginnersbook.com/2017/09/java-program-to-reverse-the-array/](https://beginnersbook.com/2017/09/java-program-to-reverse-the-array/) 该程序反转数组。例如,如果用户输入数组元素为`1,2,3,4,5`,那么程序将反转数组,数组元素将为`5,4,3,2,1`。要理解这个程序,你应该有以下 [Java 编程](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/)主题的知识: 1. [Java 中的数组](https://beginnersbook.com/2013/05/java-arrays/) 2. [Java `For`循环](https://beginnersbook.com/2015/03/for-loop-in-java-with-example/) 3. [Java `While`循环](https://beginnersbook.com/2015/03/while-loop-in-java-with-examples/) ## 示例:反转数组 ```java import java.util.Scanner; public class Example { public static void main(String args[]) { int counter, i=0, j=0, temp; int number[] = new int[100]; Scanner scanner = new Scanner(System.in); System.out.print("How many elements you want to enter: "); counter = scanner.nextInt(); /* This loop stores all the elements that we enter in an * the array number. First element is at number[0], second at * number[1] and so on */ for(i=0; i<counter; i++) { System.out.print("Enter Array Element"+(i+1)+": "); number[i] = scanner.nextInt(); } /* Here we are writing the logic to swap first element with * last element, second last element with second element and * so on. On the first iteration of while loop i is the index * of first element and j is the index of last. On the second * iteration i is the index of second and j is the index of * second last. */ j = i - 1; i = 0; scanner.close(); while(i<j) { temp = number[i]; number[i] = number[j]; number[j] = temp; i++; j--; } System.out.print("Reversed array: "); for(i=0; i<counter; i++) { System.out.print(number[i]+ " "); } } } ``` 输出: ```java How many elements you want to enter: 5 Enter Array Element1: 11 Enter Array Element2: 22 Enter Array Element3: 33 Enter Array Element4: 44 Enter Array Element5: 55 Reversed array: 55 44 33 22 11 ``` 看看这些相关的 [java 程序](https://beginnersbook.com/2017/09/java-examples/): 1. [Java 程序:反转字符串](https://beginnersbook.com/2017/09/java-program-to-reverse-words-in-a-string/) 2. [Java 程序:反转字符串](https://beginnersbook.com/2017/09/java-program-to-reverse-a-string-using-recursion/) 3. [Java 程序:反转数字](https://beginnersbook.com/2014/01/java-program-to-reverse-a-number/)