蓝桥算法训练 数组逆序排列 JAVA

问题描述
  编写一个程序,读入一组整数(不超过20个),并把它们保存在一个整型数组中。当用户输入0时,表示输入结束。然后程序将把这个数组中的值按逆序重新存放,并打印出来。要求:(1)只能定义一个数组;(2)在交换两个数组元素的值时,必须使用单独定义的一个函数swap。例如:假设用户输入了一组数据:7 19 -5 6 2 0,那么程序将会把前五个有效数据保存在一个数组中,即7 19 -5 6 2,然后把这个数组中的值按逆序重新存放,即变成了2 6 -5 19 7,然后把它们打印出来。
  输入格式:输入只有一行,包括若干个整数,最后一个整数是0。
  输出格式:输出只有一行,包括若干个整数,即逆序排列后的结果。
输入输出样例
样例输入
7 19 -5 6 2 0
样例输出
2 6 -5 19 7

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		ArrayList<Integer> list = new ArrayList<Integer>();    // 采用集合存储数据
		for (int a = sc.nextInt(); a != 0; a = sc.nextInt()) { // 读取数据
			list.add(a);
		}
		Collections.reverse(list);                             // 将数列翻转
		for (int i : list) {                                   // for-each 遍历输出
			System.out.print(i + " ");
		}
	}

这个是调用方法,更麻烦一点。


public class Main {
	private static int[] arr;

	public static void main(String[] args) throws Exception {

		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String[] s = in.readLine().split(" ");
		arr = new int[s.length - 1];
		int i = 0;
		for (String ss : s) {
			if (ss.equals("0"))
				break;
			arr[i] = Integer.parseInt(ss);
			i++;
		}
		i = 0;
		int j = arr.length - 1;
		while (i < j) {
			swap(i, j);
			i++;
			j--;
		}
		for (i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
	}

	private static void swap(int i, int j) {

		int temp;
		temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}

小剧场:认识自己,是为了寻找还没有认识的自己。

发布了108 篇原创文章 · 获赞 113 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43771695/article/details/104653853