Write a Java program that detects the duplicate characters in a string.
Certainly! Below is a simple Java program that detects duplicate characters in a given string. The program uses a HashMap
to count the occurrences of each character and then identifies which characters are duplicates.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class DuplicateCharacterDetector {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user for input
System.out.print("Enter a string: ");
String input = scanner.nextLine();
// Call the method to find duplicates
findDuplicateCharacters(input);
scanner.close();
}
private static void findDuplicateCharacters(String str) {
// Create a HashMap to store character counts
Map<Character, Integer> charCountMap = new HashMap<>();
// Count occurrences of each character
for (char c : str.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
// Print duplicate characters
System.out.println("Duplicate characters:");
boolean hasDuplicates = false;
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + ": " + entry.getValue() + " times");
hasDuplicates = true;
}
}
if (!hasDuplicates) {
System.out.println("No duplicate characters found.");
}
}
}
HashMap
to count how many times each character appears in the string.If the user inputs the string "programming", the output will be:
Duplicate characters:
r: 2 times
g: 2 times
You can run this program in any Java development environment or online Java compiler.