Casting from a char to int | SoloLearn: Learn to code for FREE!

+1

Casting from a char to int

Never work this code no matter what I use It does not work import java.util.Scanner; class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); char a = read.next().charAt(0); // int c= Integer.toString(a).charAt(0); // int c = Integer.parseInt(a); // int c = (int) a.charAt(0); // int c = (char) (a+1); // int c = Character.getNumericValue(a); int c = Integer.parseInt(String.valueOf(a)); //int c = a; // a = (c); int c = (int) a.charValue() System.out.println(c); //your code goes here }

4/10/2021 11:33:53 AM

Sana Omar

2 Answers

New Answer

+2

What are you trying to do? To assign a char value to an integer use the assignment operator = Scanner read = new Scanner(System.in); char a = read.next().charAt(0); int c = a; System.out.println(c); This will print the UTF code for the character. The static method Character.getNumericValue(char a) returns the numeric value represented by the character where the characters '0' - '9' return the integer value 0 to 9 and the letters 'A' - 'Z', or 'a' - 'z' return the integer values 10 to 35.

+1

char a = '3'; char b = '4'; int c = Character.getNumericValue(a); int d = Character.getNumericValue(b); int r = c + d; System.out.println(r);