Java Program to Detect Duplicate Characters in a String

사용하여 응답함: GPT-4o-mini에 의해Java Q&A Hub

질문:

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.");
        }
    }
}

How the Program Works:

  1. Input: The program prompts the user to enter a string.
  2. Counting Characters: It uses a HashMap to count how many times each character appears in the string.
  3. Identifying Duplicates: After counting, it checks the map for characters that appear more than once and prints them along with their counts.
  4. Output: If there are duplicate characters, it displays them; otherwise, it informs the user that no duplicates were found.

Example Usage:

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.