数组中元素前后互换

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /*从键盘输入10个数,将1和10互换,2和9互换,依此类推 该程序考察输入缓冲,异常处理 */ public class HuHuan { public static int[] write() { int[] array = new int[10]; BufferedReader[] buf = new BufferedReader[10];// 缓冲数组 int n;// 开关和中间量 for (int i = 0; i < 10; i++) { buf[i] = new BufferedReader(new InputStreamReader(System.in)); // 给每个缓冲区定义 do { n = 1; System.out.print("请输入第" + (i + 1) + "个整数:"); try { array[i] = Integer.parseInt(buf[i].readLine()); } catch (NumberFormatException e) { System.out.println("数据输入有误,请重新输入。"); n = 0; } catch (IOException e) { e.printStackTrace(); } } while (n == 0); } return array; } public static void main(String[] args) { print(); } private static void print() { int[] a = write(); int s; System.out.println("您输入的数组是:"); for (int i = 0; i < 10; i++) {// 输出原数组 System.out.print(a[i] + " "); } for (int i = 0; i < 5; i++) {// 互换 s = a[i]; a[i] = a[9 - i]; a[9 - i] = s; } System.out.println(); System.out.println("互换后的数组是:"); for (int i = 0; i < 10; i++) System.out.print(a[i] + " "); } }

你可能感兴趣的:(数组中元素前后互换)