1

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

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

This and then I realized using floor() made sb = "0.001" so the count was 4 (but not 5 with the "."?) Thanks
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.