• Post Reply Bookmark Topic Watch Topic
  • New Topic

Return most repeated character from a string  RSS feed

 
Nina Jack
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I started learning Java yesterday and have no prior programming experience. I'm doing some practice problems before class starts tomorrow so I can get a better understanding of it. The practice problems asks to return the most commonly repeated character from a given list.

I am not sure what I am doing wrong, but the error I get is: String index out of range: 4



What I currently have is:
 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Don't you mean j++ ?>
 
Nina Jack
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THANK YOU! Even after you answered I had to stare at it a bit to spot the difference. Maybe I should use different variables lol.
 
Rodion Gork
Ranch Hand
Posts: 47
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Huh... Despite several years experience with java and many years with coding in general I have this mistake while copy-pasting for-loops (either putting "j" where "i" should be, or putting "++" in the down-counting loop) at least once per month!

And by the way, when posting code in the message, you could select it and click button "Code" above the editing area - this will surround it in the special [ code ] tags so that it is pretty printed / aligned, which is quite usable for longer snippets!
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rodion is right about [code] tags. I added them for you this time. Doesn't it look better?
Please read this: UseCodeTags. (this is a link)
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch

There is a more complicated but better approach to counting which you can find in the Java™ Tutorials. That example counts words, but you should be able to amend it to count letters.

If you actually have a List (rather than a list) you can probably get a Stream out of it, which is a newer Java8 construct, and get the Stream to do your counting but I am not sure at the moment how to do that.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!