user6275518
user6275518

Reputation:

Java method CharAt crashes at comparing to #

So what I want to do is to see if a string starts with a # in a text file. However when I call the comparison of charAt(0) with # it gives out an error.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(Unknown Source)
    at StringTranslator.main(StringTranslator.java:63)

The code itself looks like this(well the part that does all the comparison)

String line;
line = br.readLine())
if(line.charAt(0) == '#')
{
    // this is a comment line ignore it
    writer.println(line);

}

Any suggestions how to outcome this and make it recognize the # symbol? Thank you in advance! Note: I am using UTF-8 encoding in both writing file in notepad and reading file in code!

Upvotes: 1

Views: 138

Answers (4)

Martin Čuka
Martin Čuka

Reputation: 18438

You need to check if string is not empty or not null and then check what character is at index 0

if (!StringUtils.isEmpty(line) && line.startsWith("#")) {
    // do something
}

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140299

It's not about the octothorpe, it's that you are reading an empty string.

If you want to check if the line starts with #, handling the empty string, use:

line.startsWith("#")

Upvotes: 4

bhspencer
bhspencer

Reputation: 13560

The error "String index out of range: 0" means you have a string that does not have any characters, which is to say the empty string.

Upvotes: 0

Mureinik
Mureinik

Reputation: 311028

The crash is unrelated to the #. You're attempting to evaluate the first character in an empty string. You should verify the string isn't empty before accessing its characters:

if (line.length() > 0 && line.charAt(0) == '#')

Upvotes: 0

Related Questions