java/labs/lab10/CountLettere.java
2024-12-31 14:58:42 +03:00

36 lines
1.1 KiB
Java

// ****************************************************************
// CountLetters.java
//
// Reads a words from the standard input and prints the number of
// occurrences of each letter in that word.
//
// ****************************************************************
import java.util.Scanner;
public class CountLetterse
{
public static void main(String[] args)
{
int[] counts = new int[26];
Scanner scan = new Scanner(System.in);
//get word from user
System.out.print("Enter a single word (letters only, please): ");
String word = scan.nextLine();
//convert to all upper case
word = word.toUpperCase();
//count frequency of each letter in string
for (int i=0; i < word.length(); i++) {
try {
char current = word.charAt(i);
counts[word.charAt(i)-'A']++;
}
catch (Exception e){
System.out.println("Reason for error:"+"!"+(char)word.charAt(i)+"!");
}
}
//print frequencies
System.out.println();
for (int i=0; i < counts.length; i++)
if (counts [i] != 0)
System.out.println((char)(i +'A') + ": " + counts[i]);
}
}