• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Probably Simple But I Need Assistance - Printing Out All Escape Characters

 
John Douglas
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All

I am attempting to write a very simple Java program that prints out all escape characters between 0 and 255. Here is what I have but it, obviously, does not work:


Whenever I attempt to compile, I get this error:



Like I said, this is probably easy but I'm not sure how to do it.

Thanks for reading and have a good day.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The \ sequence is interpreted by the compiler before compilation starts, so it reads \u00 as an error because \u is supposed to be followed by 4 (hexadecimal) digits/0. I am not convinced I would call those escape characters; that range includes mostly ordinary characters.

You realise you can cast an int to a char and print that with the %c tag? That might be a lot easier.
 
John Douglas
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Converting an int to a char worked perfectly ... thank you. I was simply under the assumption that I had to use the escape character and the hexidecimal value of the character I was wanting to print.

Thanks again
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome Have a look at the Java™ Language Specification definition of what a char really is.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code will have a problem if the HEX representation is just one character. Fortunately, Java 6 came with java.util.Formatter which is integrated into String.format and PrintStream.printf:
This will print \u, followed by i in 4 HEX digits (x makes it HEX, 04 gives it width 4 filling empty slots with 0).
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I tried that earlier. If you print "\\" + 'u' + String.format("%04x", i), you get \u0056 or similar displayed on screen.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic