Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Convert number to character of that value

 
John Warner
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I convert say
int num = 65;
to a character value of "A"
that is the decimal 65 is the letter A in Ascii. I need to know how to force this conversion. I tried
char c;
c = (char)num;

the compiler refuses to do the convert. Note I do not want the digits 6 and 5, I want the letter A as output. Is this even possible with Java?

In basic you have the chr(65) function which returns the letter A. I'm looking for the same functionality. Ulitmately I want to use math.random to generate some random letters.

Thanks for help a newb.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

What you've shown is perfectly fine -- don't know why you couldn't get it to work. If you show an actual code example that won't compile for you, we could tell you what the problem is with it. But

int i = 65;
char c = (char) i;

will work perfectly.
[ September 03, 2006: Message edited by: Ernest Friedman-Hill ]
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dude...Works fine for me in eclipse.

Here's the whole class:

class CharTest {
public static void main(String args[]) {
int num = 65;
char c;
c = (char)num;
System.out.println(c);
}
}

Cheers!
 
John Warner
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fellas, thanks, I found my error. I was trying to return a String from the function that I was doing the convert in. As soon as I added a Character.toString(myChar) everything fell into place. My real problem was thinking the compiler was not going to allow this at all rather then me nit understanding what had to be done. Once you both said 'hey this works' I started looking harder at my code.

Thanks again!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic