-2

I've been trying to convert a character to ASCII. Please help out, here is my code.

import java.util.*;
public class CharToAscii {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("ENter the character you want to convert");
        char c = sc.next().charAt(0);
        System.out.println(int(c));
    }
}
Jiahao Cai
  • 1,222
  • 1
  • 11
  • 25
Srjk
  • 19
  • 2
  • 5
  • 2
    should be `System.out.println((int)c);` . – Ousmane D. May 28 '17 at 02:35
  • possible duplicate: https://stackoverflow.com/questions/16458564/convert-character-to-ascii-numeric-value-in-java – Eric May 28 '17 at 02:36
  • @Aominè got the answer. You seem to be using `int(c)` as if it is a function, which it isn't. You're trying to cast between data types, and to do this you put the parenthesis around the data type you're casting the data to. – Flaom May 28 '17 at 02:40
  • 1) I should point out that this question's title and description is ambiguous. Based on the code, you are **actually** trying to convert the character to the *decimal representation* of an ASCII character code. 2) For characters in the ASCII range (0x00 to 0x127) the number will be what you expect. For others ... well ... the character is strictly not-convertable ... and what you will see is a UTF-16 code-unit, representing the character, or part of it. – Stephen C May 28 '17 at 02:58
  • To @StephenC's point. there is a problem with expecting ASCII at all. Most people responding to the prompt "Enter the character you want to convert" would not expect a limitation of [C0 Controls and Basic Latin](http://www.unicode.org/charts/nameslist/index.html) characters. Some might type letters from their name, say "é" or "శ్రీ" (["\u0c36\u0c4d\u0c30\u0c40"](http://javajee.com/unicode-escapes-in-java)). I might type the character "…" or my favorite punctuation mark "—" or favorite symbol "". Java supports them all, as do most web pages—including this one. _Unicode…since 1991™._ – Tom Blodget May 28 '17 at 19:49

1 Answers1

0
System.out.println(int(c));

Line gives the ERROR

TypeCasting should be done by placing the type in round braces.

System.out.println((int)(c));

Is the CORRECT implementation.

Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27
  • Ermm .... this ignores the fact that not all `char` values map to an ASCII character. Hence "CORRECT" is an overstatement. – Stephen C May 28 '17 at 05:35