Cyaena Cyaena - 6 days ago 5
Java Question

Want to switch character '\'

I want to switch-case the character \ but it is not working as I intend.
Because the character skips over the character after it, what would be the ' of the character literal. So I tried to do it as UTF. But it still does not work. Here is my code:

switch(input.charAt(i)){
case '\u005C':
actVel ++;
break;
case '_':
if(actVel == 0)
{
actVel++;
plusCount++;
}
else
{
flat++;
}
break;


I am getting "Unclosed character literal" as error code.
I would be really grateful for an answer. Thanks :)
- Cyaena

Answer

The \ is a special escape character.

Here the list of escaped characters:

  • \\ for \
  • \n for new line
  • \t for tab
  • \b for backspace
  • \r for carraige return
  • \f for form feed
  • \' for the character '
  • \" for the character "

For a single \ you need to use the special sequence \\

As an example:

System.out.println("Hello boys\\girls!");   // Prints:    Hello boys\girls!

Fro your code you need to do the following:

case '\\':
    ...
    // Your code here

From the comment to the answer of aimee.

The string _/\_ should be written as "_/\\_". The length of this String is 4 and is computed as follow:

_   1 character
/   1 character
\\  1 character (printed as \)
_   1 character
Comments