• Post Reply Bookmark Topic Watch Topic
  • New Topic

Mysterious exception  RSS feed

 
Josh Galeigh
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given a program and told that the program could crash with this error:

t's possible to make the game die with an exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at Game.main(Game:41)

Line 41 just has y += dy;

Before I have to post the whole code I'm trying to understand what exactly the problem is. That line in the code is for actually moving a string across the screen in the vertical direction. But I don't know why I'd get an out of bounds exception. Is this telling me the string is too long?? Or is it saying the string length is 0?
 
Daryl Cofer
Greenhorn
Posts: 19
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Taken from the Java API:

public class StringIndexOutOfBoundsException
extends IndexOutOfBoundsException
Thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string

So it looks like the length of your String could potentially be 0.

Why don't you try printing the length of the String in question to the console before you call the charAt() method?
 
Josh Galeigh
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I understand. The charAt() is in another class that was built for the course. So I can't make any changes to it. However I just added 1 to the text string so it should never have anything less than 1. I think that fixed it. I was able to get the error when I manually set it to zero.

I read the Java API but it didn't really sink in until you said the string could be zero. The charAt() messed me up as well since I didn't have it in my program at all.

Thanks for the help.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think there is a much better fix. If you always require Strings to have a “first character”, you should ensure that empty Strings "" do not get into your program in the first place.
  • 1: Get all the String reading done in one place.
  • 2: Throw an IllegalArgumentException if any of the Strings is the wrong length.
  • 3: Throw a NullPointerException if you get nulls. You can get nulls from JOptionPane, but I think maybe not from Scanner of BufferedReader.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!