To find the sum of the repeated numbers in an array in Java, you can use a loop to iterate through the array and use a counter to keep track of the number of times each number appears. Here’s an example of how you can do this:

Copy codeint[] numbers = {1, 2, 3, 2, 3, 4, 3};
int sum = 0;

// Create a map to store the number of times each number appears
Map<Integer, Integer> counts = new HashMap<>();

// Iterate through the array and count the number of times each number appears
for (int number : numbers) {
  int count = counts.getOrDefault(number, 0);
  counts.put(number, count + 1);
}

// Iterate through the map and add the sum of the repeated numbers
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
  int number = entry.getKey();
  int count = entry.getValue();
  if (count > 1) {
    sum += number * count;
  }
}

System.out.println("Sum of repeated numbers: " + sum);

This code first creates a Map to store the number of times each number appears in the array. It then iterates through the array and uses the put method to add each number to the map and increment its count. Finally, it iterates through the map and adds the sum of the repeated numbers (i.e. numbers that appear more than once) by multiplying the number by its count.

(Visited 6 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window