Java: Parse Int Value from a Char

Java: parse int value from a char

Try Character.getNumericValue(char).

String element = "el5";
int x = Character.getNumericValue(element.charAt(2));
System.out.println("x=" + x);

produces:

x=5

The nice thing about getNumericValue(char) is that it also works with strings like "el٥" and "el५" where ٥ and are the digits 5 in Eastern Arabic and Hindi/Sanskrit respectively.

How can I convert a char to int in Java?

The ASCII table is arranged so that the value of the character '9' is nine greater than the value of '0'; the value of the character '8' is eight greater than the value of '0'; and so on.

So you can get the int value of a decimal digit char by subtracting '0'.

char x = '9';
int y = x - '0'; // gives the int value 9

error while parsing an int from a char in String

That method you are calling parseInt(String, int) expects a radix; something that denotes the "number system" you want to work in, like

parseInt("10", 10) 

(10 for decimal)! Instead, use

Integer.parseInt(i)

or

Integer.parseInt(i, 10)

assuming you want to work in the decimal system. And to explain your error message - lets have a look at what your code is actually doing. In essence, it calls:

Integer.parseInt("123", '1') 

and that boils down to a call

Integer.parseInt("123", 49) // '1' --> int --> 49! 

And there we go - as it nicely lines up with your error message; as 49 isn't a valid radix for parsing numbers.

But the real answer here: don't just blindly use some library method. Study its documentation, so you understand what it is doing; and what the parameters you are passing to it actually mean.

Thus, turn here and read what parseInt(String, int) is about!

What's the java way of converting chars (digits) to ints

How about Character.getNumericValue?

Java thinks I want to convert char to String using Integer.parseInt()

Try

return Integer.parseInt("" + cases2[0]);

By adding to the empty string "" you convert to a string, which is the right type for Integer.parseInt.

How do I convert a char [] to an int?

char[] c = {'3', '5', '9', '3'};
int number = Integer.parseInt(new String(c));

How can I convert string to integer and access each individual char in string as integer?

This is very easy, to get your String as an integer use:

no = Integer.parseInt(s);

And if you wish to convert it to a char array use:

char[] charArray = ("" + no).toCharArray();

Then if you wish to get an int from a specific char you can use:

int x = Character.getNumericValue(charArray.charAt(0)); // or any index instead of 0


Related Topics



Leave a reply



Submit