YaboyBenji YaboyBenji - 9 days ago 5
Java Question

Write a program that will read a line of text, and will display all letters in the text along with the number of times the letter appears in the text

I have the basics, but I need to make it so that my program will work without printing the unused letters of the alphabet at the end, say my sentence is "dog" I would want the output to be: D-1
O-1
G-1, instead of A-0 B-0 D-1, and so on. Thanks for any help provided, it is greatly appreciated.

what I have so far is:

package as10;

import java.util.*;

public class as
{

private static void countLetters(String sentenceString)
{
int[] array = new int[26];
sentenceString = sentenceString.toUpperCase();

for (int i = 0; i < sentenceString.length(); ++i)
{
if (sentenceString.charAt(i) >= 'A' && sentenceString.charAt(i) <= 'Z')
{
++array[sentenceString.charAt(i) - 'A'];
}
}

for (int i = 0; i < 26; ++i)
{
System.out.println((char) ('A' + i) + " - " + array[i]);
}
}

public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
String letterString;
while (true)
{
System.out.println("Enter a line of text: ");
letterString = kbd.nextLine();

System.out.println("Letter Frequencies: ");
countLetters(letterString);

break;
}
kbd.close();
}
}

Alp Alp
Answer

so, basically, you want to opt out all chars if counter is 0.

In other words, you will need an if statement around print line and only perform system output if relevant array value is non-zero.

Above statement is in pure English. It is again your assignment to convert that sentence into java, as I refuse to do your homework on your behalf.

Does it sound fair ? :)

Comments