charAt() for numbers?
Hey everyone,
Kinda new to Java and I am running into a problem. It will not let me use charAt() to retrieve a specific number from a larger number. (e.g. 234 and all I want is the 2 in the hundreds) Gives me an error.
I was wondering if there was a function that could return the value of a certain decimal place in a larger number?
[351 byte] By [
RyanSN] at [2007-11-11 8:16:14]

# 1 Re: charAt() for numbers?
You cannot invoke methods on primitive data types. Also, the charAt(int) method is only found in the String class, StringBuffer class and StringBuilder class. What you could do is convert the integer into a String, then use the charAt(int) method on that.
public int charAt(int num, int index) {
String a = String.valueOf(num);
return a.charAt(index);
}
Or, simplified:
public int charAt(int num, int index) {
return String.valueOf(num).charAt(index);
}
With that you can do charAt(234, 0);.
destin at 2007-11-11 22:36:00 >

# 2 Re: charAt() for numbers?
I think destin's solution is more appropriate. But just to get think you about other possibilities you can try combinations of "/" (division) and % (modulus) symbols to possibly achieve similar results.
example:
public class Modulus {
public static void main(String[] args) {
int i = 234;
int firstDigit = 234/100;
int secondDigit = 234%100/10;
int thirdDigit = 234%100%10;
System.out.println(firstDigit);
System.out.println(secondDigit);
System.out.println(thirdDigit);
}
}
arul at 2007-11-11 22:36:55 >

# 3 Re: charAt() for numbers?
I suggest to convert the int to a string through String number = Integer.toString(1234);
then you can process as you like. but you should consider a "-" sign, if the number was negative, when using the charAt on that string.
With the Integer class, you also can reconvert your character to an integer (Integer.parseInt(String))