Reputation: 11
I want to create a program to output the number of occurrences of a letter in a word. Basicaly the output has to look like this:
Please enter a word—howdy
The word howdy has five characters.
What letter would you like to guess? (enter zero to quit) a
There are 0 A’s.
What letter would you like to guess? (enter zero to quit) b
There are 0 B’s.
This is what I got so far:
import java.util.Scanner;
public class LetterOccurence
{
public static void main(String[]args)
{
Scanner input=new Scanner(System.in);
String word;
String letter;
int letterNumber;
boolean [] alphabet = new boolean [27];
System.out.println("Please enter a word- ");
word=input.next();
System.out.println("The word "+ word + " has " + word.length() + " letters\n");
String lower = word.toLowerCase();
for(letterNumber=0;letterNumber<lower.length();letterNumber++)
{
alphabet[lower.charAt(letterNumber) - 'a'] = true;
}
//do
//{
System.out.println("What letter would you like to guess? (enter 0 to quit) ");
letter = input.next();
if (alphabet[letter.charAt(0)-'a'] = true)
{
System.out.printf("There are %s's\n",letter.charAt(0));
}
else
{
System.out.printf("There are 0 %s's\n",letter.charAt(0));
}
//}while(Character.isLetter(letter.charAt(0)));
}
}
I am now stuck, any ideas on how to continue?
Upvotes: 1
Views: 2121
Reputation: 234857
You don't want a boolean array for alphabet
-- that only tells you what letters appear in the word, but not how many of each. Try this instead:
boolean [] alphabet = new boolean [27];
for(letterNumber=0;letterNumber<lower.length();letterNumber++)
{
++alphabet[lower.charAt(letterNumber) - 'a'];
}
Then later:
System.out.printf("There are %d %s's\n",alphabet[letter.charAt(0) - 'a'], letter.charAt(0));
Upvotes: 1
Reputation: 18532
For a start, boolean
s only hold a true
or false
value, you can't count with them. Rather than in your loop setting each element in the array that maps to a certain character to true
, you could simply increment the counter.
In this case you're going to require an int
as opposed to a boolean
. And to print out the amount of occurrences for a specific letter, you obviously just print out the int
value at that specific index of the array.
An alternative is also a Map<Character,Integer>
, rather than calculating the index for specific char
s in your array.
EDIT: As Dave mentioned, your if
statement is also broken.
Upvotes: 2
Reputation: 160321
If nothing else, that if
statement in your commented-out do/while
is using a single =
(assignment) instead of ==
(comparison).
All you really need to do is keep a single count per guess, initialize it to zero, and each time you encounter the guessed letter, increment it.
If you're trying to do all that work "up front" before guessing, then you don't really need a map of booleans, you need a map of ints, one per lower-case letter, initialized to zero, and incremented each time its corresponding letter is guessed.
You're very close.
Upvotes: 1