repeatreverse.java
来自「Java 入门书的源码」· Java 代码 · 共 52 行
JAVA
52 行
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.
/* Reverses an array. The user inputs the
* size of the array and enters its components.
*/
import iopack.Io;
public class RepeatReverse {
public static int[] readIntArray() {
int size = Io.readInt("Enter the array size");
int [] anArray = new int[size];
for (int i=0; i<size; i++)
anArray[i] = Io.readInt("Enter anArray["+i+"]");
return anArray;
}
public static void reverse(int [] anArray) {
int temp; // used to store a value during a swap
int left = 0; // index of the left element to swap
int right = anArray.length -1; // index of the right element to swap
while (left < right) {
temp = anArray[left];
anArray[left] = anArray[right];
anArray[right] = temp;
right--;
left++;
}
}
public static void display(int [] anArray) {
System.out.print("{");
for (int i=0; i<anArray.length; i++) {
if (i!=0) System.out.print(",");
System.out.print(anArray[i]);
}
System.out.println("}");
}
public static void main(String [] args) {
char repeat; // 'Y' to repeat, 'N' to quit
int [] theArray; // the array to reverse
do {
theArray = readIntArray();
System.out.print("The input array is ");
display(theArray);
reverse(theArray);
System.out.print("The reversed array is ");
display(theArray);
repeat = Io.readChar("Enter 'Y' to repeat, 'N' to quit");
} while (repeat == 'Y' || repeat == 'y');
Io.readString("Press any key to exit"); // Added for IDE use
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?