Write a java program to find unique even sum

Write a program to read an array, eliminate duplicate elements and calculate the sum of even numbers (values) present in the array.

The return type (integer) should be the sum of the even numbers. In case there is no even number it should return -1.

Input and Output Format:

Input consists of n+1 integers. The first integer corresponds to n, the number of elements in the array. The next ‘n’ integers correspond to the elements in the array.

In case there is no even integer in the input array, print no even numbers as output. Else print the sum.

Refer sample output for formatting specifications.

Assume that the maximum number of elements in the array is 20.

Sample Input 1:

4

2

5

1

4

Sample Output 1:

6

Sample Input 2:

3

1

1

1

Sample Output 2:

no even numbers

Find unique even sum in Java.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int a[] = new int[n];
    for (int i = 0; i < n; i++) {
      a[i] = sc.nextInt();
    }

    System.out.println(sumOfEvenNos(a));
  }

  public static int sumOfEvenNos(int[] a) {
    int sum = 0;
    LinkedHashSet<Integer> hm = new LinkedHashSet();
    for (int i = 0; i < a.length; i++) {
      hm.add(a[i]);
    }

    Iterator<Integer> lm = hm.iterator();
    while (lm.hasNext()) {
      int b = lm.next();
      if (b % 2 == 0)
        sum = sum + b;
    }
    return sum;
  }
}

Add a Comment

Your email address will not be published. Required fields are marked *

nineteen − five =