Question

I want to loop through a StringBuffer and use the value of each char to calculate the output. Debug shows that when I pass in 10 that sb.length() is 4 even though it should be 2. Should I be using different methods?

    public double ConvertDecimal(double in) {

    double out = 0;

    sb = new StringBuffer(String.valueOf(Math.floor(in));

    sb.reverse();

    for (int i = 0; i < sb.length(); i++) {

        out += Double.valueOf(sb.charAt(i)) * Math.pow(3,i);

    }

    return Math.floor(out);

}

For passing in "10" the first iteration makes out=48 and I don't understand where it's going wrong when I want the following:

in = 10

sb.reverse = "01"

//first iteration of loop - char at first position of sb.reverse being 0 out += Double.valueOf(sb.chartAt(0)) * Math.pow(3,0);

//second iteration of loop - char at second position of sb.reverse being 1 out += Double.valueOf(sb.chartAt(1)) * Math.pow(3,1);

return out; //out should be 3

Was it helpful?

Solution

If you look at http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html#reverse() you will see that reverse returns a new StringBuffer

so change your code to

sb = sb.reverse();

Also as you are using Intergers not Doubles, then why are you casting the char to a double?

try

int x = Character.getNumericValue(sb.charAt(i));
out +=  x * Math.pow(3,i);

OTHER TIPS

At

Double.valueOf(sb.charAt(i))

the character '0' is cast to a double, but its value is 48, not 0.

Also, you need to use the value returned by sb.reverse(), rather than the original sb.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top