• Post Reply Bookmark Topic Watch Topic
  • New Topic

StringIndexOutOfBoundsException?  RSS feed

 
Jackson Blackwale
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically I am making a program that reads a .java file then makes a new output .txt file with that code minus the commented lines.

Here is part of my code but I don't understand why it doesn't work:



So if both the first and second character of the line is /, the line isn't printed to new .txt file and the while loop goes to the next line.


This is my error message:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at CommentRemover.main(CommentRemover.java:41)

 
Phil English
Ranch Hand
Posts: 62
MySQL Database Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looks like it is having difficulty with one of you line variables. If it was me I'd put System.out.println(line) in before the if statement and see if I could spot the issue. Specifically, what does your code do if it encounters an empty line?

See also this post which is actually one of the 'similar thread' links below
 
Jackson Blackwale
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If my code encounters an empty line I would still want it to be printed. Only full line comment lines should not be printed.
 
Phil English
Ranch Hand
Posts: 62
MySQL Database Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed. But on every line it tries to read the first character. What is the first character on an empty line?
 
Jackson Blackwale
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
True. Perhaps I should do a check if it is an empty line first and then proceed from there. Thanks for the idea!
 
Jackson Blackwale
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Phil English wrote:Indeed. But on every line it tries to read the first character. What is the first character on an empty line?


You were right thank you. I get it now. The length of an empty line is 0, so checking the character at length(1) would be why I was getting out of bound error.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!