This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Actually this is my friend's doubt.. The logic she has come up with is as following:
public class numerology
public static void main(String args)
int idx=0; int tokenCount;
String words=new String ;
String message="a b a b a b";
StringTokenizer st=new StringTokenizer(message);
System.out.println("Number of tokens = " + tokenCount);
while (st.hasMoreTokens()) // is there stuff to get?
for (idx=0;idx<tokenCount; idx++)
I tried it out and got a bunch of stars! I was expecting some magic number which would make me rich and famous!
On a serious note, one way to approach the problem would be
1) Define a collection of characters. Since you are interested in the index of the characters, I would suggest a java.util.List
2)String has a charAt method which you can use to extract individual characters from the index string
3)Once you get the individual character, look up its index. The List has a useful indexOf() method which you can choose.
4) Figure out all indices and let the user know the magic number.
String equality is tested with the "equals" method, not with "==". If, on the other hand, you're after character equality -which makes more sense here- then you need to use single quotes instead of double quotes.
If this was my problem, then a "Map<Character, Integer>" would feature in it prominently. It would have the characters I wanted to count as keys ('a', 'b', etc.) and the numbers assigned to them as values (1, 2, etc.). That way I could avoid hardcoding either the characters or the numbers in the code that does the counting; those would only occur in the code that sets up the Map, thereby making changes much easier.