如何在不使用集合的情况下按降序打印偶数和奇数的偶数

时间:2015-06-13 10:57:18

标签: java

输入:

10
3 1 45 67 2 56 89 22 11 69

输出(我想要的):

2 22 56 
89 69 67 45 11 3 1

我想按升序打印偶数数字,按降序打印奇数而不使用集合,因为我不知道收集。在这里帮助我,我如何按降序打印奇数我能够直到偶数

代码:

import java.util.Arrays;
import java.util.Scanner;

class T {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner(System.in);
        System.out.println("enter a number");
        int n = sc.nextInt();

        int s[] = new int[n];
        int i;
        for (i = 0; i < n; i++) {
            int e = sc.nextInt();
            s[i] = e;
        }

        Arrays.sort(s);
        for (int j = 0; j < n; j++) {

            if (s[j] % 2 == 0) {
                System.out.println(s[j]);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

<强>代码:

import java.util.Arrays;
import java.util.Scanner;

class T {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner(System.in);
        System.out.println("enter a number");
        int n = sc.nextInt();

        int s[] = new int[n];
        for (int i = 0; i < n; i++) {
            int e = sc.nextInt();
            s[i] = e;
        }

        Arrays.sort(s);
        // Even in ascending
        System.out.println("\nEven numbers in ascending order:");
        for (int j = 0; j < n; j++) {

            if (s[j] % 2 == 0) {
                System.out.print(s[j] + " ");
            }
        }

        // Odd in descending
        System.out.println("\nOdd numbers in descending order:");
        for(int j = (n -1); j >= 0; j--) {
            if (s[j] % 2 == 1) {
                System.out.print(s[j] + " ");
            }
        }
    }
}

<强>输出:

enter a number
10
3 1 45 67 2 56 89 22 11 69

Even numbers in ascending order:
2 22 56 
Odd numbers in descending order:
89 69 67 45 11 3 1 

<强>解释

由于数组已经排序(按升序排列),请先打印出偶数。
然后以相反的方向(desc顺序)遍历数组,并打印出奇数。

答案 1 :(得分:0)

反转标记并使用相同的循环打印:

duration
相关问题