Problem:
Input a character from the user and display its ASCII value on the screen.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /** * @author Hafiz Muhammad Umer */ import java.util.Scanner; public class ASCIICodes { public static void main(String[] args) { Scanner in=new Scanner(System.in); System.out.print("Enter a character: "); String s=in.nextLine(); System.out.println("ASCII value: "+(int) s.charAt(0)); } } |
Output:
Enter a character: ? ASCII value: 63
Enter a character: k ASCII value: 107
Explanation:
- The program inputs a string from the user at line 11. We have taken a string as an input because we can not directly take a character from the user as input.
- At the line 12, the ASCII code is determined and displayed on the screen. Actually first string is converted to char using charAt() function and then that char is converted to its ASCII value by placing (int) before it. Remember that we can convert a char to int which will store the char's ASCII value in the int.
0 Comments
Thanks for leaving a comment. I will try to reply you soon.