Write a Java program that detects the duplicate characters in a string. What if I don't let you use the collection class in Java?
Certainly! Below is a Java program that detects duplicate characters in a string without using any collection classes. Instead, it uses a simple array to keep track of the occurrences of each character.
import java.util.Scanner;
public class DuplicateCharacterDetector {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
// Call the method to find duplicates
findDuplicateCharacters(input);
scanner.close();
}
public static void findDuplicateCharacters(String str) {
// Create an array to keep track of character counts
int[] charCount = new int[256]; // Assuming ASCII characters
// Count occurrences of each character
for (int i = 0; i < str.length(); i++) {
charCount[str.charAt(i)]++;
}
// Print duplicate characters
System.out.println("Duplicate characters in the string:");
boolean hasDuplicates = false;
for (int i = 0; i < charCount.length; i++) {
if (charCount[i] > 1) {
System.out.println((char) i + " appears " + charCount[i] + " times.");
hasDuplicates = true;
}
}
if (!hasDuplicates) {
System.out.println("No duplicate characters found.");
}
}
}
charCount
of size 256 (to accommodate all ASCII characters) to count the occurrences of each character in the string.charCount
array for any character that appears more than once and prints those characters along with their counts.