Getting incorrect output for my charAt funciton

41 Views Asked by At

I have this function, and for some reason even though str =30, and i=0, str.charAt(i) gives me 51.

private static void handleArmstrong(int parameter) {
    int number;
    for (number = 0; number < parameter+1; number++) {
        String str= Integer.toString(number);
        int len=str.length();
        double result=0;
        for (int i = 0; i < len; i++) {
            int base= str.charAt(0);
            result=+Math.pow(base,len);
        };
    }
}
1

There are 1 best solutions below

2
AminM On BEST ANSWER

You are getting an int instead of a char because you are implicitly converting the char into an int in this line:

int base= str.charAt(i);

You can convert the character to a number like this:

int base= Integer.parseInt(str.substring(i,i+1));

This will throw an exception if the substring is not a number so you'll need to handle that.