5

I need to do this:

while (result2.charAt(j) != '\'){
    
}

I get an error saying: Invalid character constant.

Why? And how can I get over it?

djm.im
  • 3,295
  • 4
  • 30
  • 45
Unknown user
  • 44,551
  • 16
  • 38
  • 42

7 Answers7

9

The backslash is a special character and it needs to be escaped with another backslash. Like this:

while (result2.charAt(j)!='\\'){

}
Asaph
  • 159,146
  • 25
  • 197
  • 199
3

Use '\\'. It's because backslash is used in escape sequence like '\n'. With a single \ the compiler have no way to know.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
2

Looks like you need to escape the backslash. Try

while (result2.charAt(j)!='\\'){

    }
SquidScareMe
  • 3,108
  • 2
  • 24
  • 37
0

I got this similar error in Eclipse for Android although for different situation, and I just figured out that in Java you cannot enclose a string (multi-character word) in single quotes. So you need to have like - "sampleword" strings enclosed in double quotes rather than single quote to get rid of such error thought I could just share it here for others to refer..

ameyx
  • 403
  • 5
  • 9
0

Same error here, but using unicode character representation.

005C is backlash character. Need to escape it: "\u005C" .

Example:

str = str.replace("\\u005C", "'\\u005C'");
live-love
  • 48,840
  • 22
  • 240
  • 204
0

You need to escape it I think,

So you need to do

while(results2.charAt(j)!='\\')
{
}

I think that's the solution I think

0

you need an extra character '\'

" " " == " \" "


" \ " == " \\ "
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417