labs
This commit is contained in:
36
labs/lab10/CountLettere.java
Normal file
36
labs/lab10/CountLettere.java
Normal file
@ -0,0 +1,36 @@
|
||||
// ****************************************************************
|
||||
// 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]);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user