Link to home
Start Free TrialLog in
Avatar of comptitbits
comptitbits

asked on

Java find the ascii value

Dear Experts,

I need your advice.

I want to enter any character (digits, letters and +)(*&^%$ etc) using the key board
and find the equivalent ASCII value of the character in Java.

Please let me know if there is any function or a easy way to do this.

500 points for the best answer

Thank you very much

Avatar of mbodewes
mbodewes
Flag of Netherlands image

Well, first you need something to read out the string or character from the inputstream:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
charStr = br.readLine();

Now you take the first character from the String using the String.charAt() method. You might want to check if the line just contains a single character.

Now you could just display the value of the char. Char is Unicode, but the first 128 characters are equal to the ASCII code.

You could also use charStr.getBytes("ASCII"), this will give you a byte[] of ASCII character, or an exception if the character is not an ASCII character. Then you display the value of the first byte (even though the value should always be 0..127, it might be a good idea to do charValue & 0xFF the value so you won't get any negative values (e.g. if you switch to a character set that runs from 0..255.
Avatar of comptitbits
comptitbits

ASKER

Dear mbodewes:

Thanks for your prompt reply

Is there any other way like:

Print "Enter a letter"
String letter = input.next();
(find the value of letter in ascii)
Print the ascii value

Thank you very much
ASKER CERTIFIED SOLUTION
Avatar of mbodewes
mbodewes
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Two variants:
1. Using the console (System.in)
        System.out.println("Enter a character:");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int characterValue = br.read();
        System.out.println(characterValue);

2. Using a little window to prompt the user:
        String input = JOptionPane.showInputDialog("Enter a character:", "");
        byte[] characterBytes = input.getBytes();
// print first character (the following characters are ignored
       System.out.println(characterBytes[0]);
Thanks mbodewes.  It works.  But, I want to find more easier way to do this.
My aim is make the code as simple as possible by using all kinds of materials out there.  I am doing this just for fun.  Thanks a lot you got 500 points