-2

My program displays 10 digits that the user enters in reverse, but I want it to display the even numbers in reverse only. I tried doing so by writing an if statemntnumbers[i]%2=0 but it did not work. This is my code:

  Scanner input = new Scanner (System.in);

        int[] numbers = new int[10];
        System.out.println("Enter "+numbers.length+" integer numbers: ");

        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = input.nextInt();

        }
        System.out.println("\nThe reverse of entered even numbers:  ");


        for (int i = numbers.length-1; i >=0; i--) {
            System.out.print(numbers[i] + " ");
        } System.out.print("\n");    }
plants tho
  • 47
  • 6
  • 3
    Please show us the code that had the `if` statement you wrote. All we know is that you wrote this, somewhere. – ajb Dec 21 '16 at 06:25
  • use `==` instead of `=' in if condition. Please go through java syntax properly. This a pretty obvious mistake. – Bopsi Dec 21 '16 at 06:40

3 Answers3

2

What you described attempting should have worked, i.e.:

for (int i = numbers.length-1; i >=0; i--) {
    if (numbers[i] % 2 == 0) {
        System.out.print(numbers[i] + " ");
    }
}

One explanation for what happened is that you literally did this if statement:

if (numbers[i]%2=0) { ... }

which would fail because you are making an assignment, not checking an equality.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Java 8 Version using Streams

int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Arrays.stream(numbers)
      .boxed()
      .sorted(Collections.reverseOrder())
      .filter(i -> i % 2 == 0)
      .forEach(System.out::println);

Update:
Output on single line with whitespace in between:

int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
String output = Arrays.stream(numbers)
                       .boxed()
                       .sorted(Collections.reverseOrder())
                       .filter(i -> i % 2 == 0)
                       .map(String::valueOf)
                       .collect(Collectors.joining(" "));
System.out.println(output);
JDC
  • 4,247
  • 5
  • 31
  • 74
  • 1
    Nice, except that the OP's code put all the output numbers on one line. As long as you're showing us how to write cool code, why don't you throw in a `joining` collector? :) – ajb Dec 21 '16 at 06:47
  • 1
    Done as requested ;) – JDC Dec 21 '16 at 07:33
0

Correct it by using statement

if (numbers[numbers.length - 1] % 2 == 0) {
    //.....
}
Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34