Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

A Strange Behaviour in my code  RSS feed

 
Ranajoy Saha
Ranch Hand
Posts: 105
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This program works like this. If you enter a sentence suppose "This is a cat", the output will be "T.I.A.C"


The input sentence used here is "This is a cat".
If I store the words before this "if(sentence.charAt(i) == ' ')" statement in the for loop the output comes "T.I.A.C." but if the store the words below "if(sentence.charAt(i) == ' ')" the output comes "T. . . ."
Why is this abnormality?
 
Ranajoy Saha
Ranch Hand
Posts: 105
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for asking such a silly question.
I figured it out my self. Actually, when I was storing words down the space character always came up front as the value of i was still the same.
Sorry guys! Be easy on me guys, I'm just a kid who reads in class 9.
 
Jam Rei
Greenhorn
Posts: 29
IntelliJ IDE Java Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if the store the words below "if(sentence.charAt(i) == ' ')" the output comes "T. . . ."

try with other delimiters, such as _ and you can see that each word begins with this delimiter

To see that do the following steps:
1. Comment out line 28 //word += sentence.charAt(i);
2. Change a line 30 to if(sentence.charAt(i) == '_')
3. Comment in line 37 //word += sentence.charAt(i);
4. Add a new line 38: System.out.println("iteration: " + i + " word: " + word);
5. Run the program and enter a sentence suppose This_is_a_cat

Hint: Clean your code, e.g. write line 25: for(int i = 0; i < sentence.length(); i++) and delete lines 20 and 23, etc...
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am afraid I shall provide the corret answer and you will hate me for it. You only need three keystrokes, but they are ctrl‑A‑delete.

Now start again. Turn your computer off and write down how you are going to get the initials. It is reasonably simple. Now find out how you ought to put Strings together. You don't use += on Strings, but a StringBuilder. Then you should have some neat and elegant code, about half the length of what you have at present.

I shall hve to change your // comments because they don't make the code easier to understand; they make the lines too long. Amd always use titles which say what the question is about.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!