-1
public class doubleSum {

    private static String calculate(String a, String b){
        String[] a_parts = a.split("\\.");
        String[] b_parts = b.split("\\.");

        StringBuffer sb = new StringBuffer();

        int[] carrier = new int[]{0};
        cal(a_parts[1],b_parts[1],sb, carrier);
        sb.append(".");

        cal(a_parts[0],b_parts[0],sb, carrier);
        if(carrier[0] > 0)
            sb.append(carrier);
        return sb.reverse().toString();
    }
    private static void cal(String a, String b, StringBuffer sb, int[] carrier) {
        int i = a.length() - 1;
        int j = b.length() - 1;
        while(i >= 0 || j >= 0) {
            int sum = carrier[0];
            if(i >= 0) {
                sum += a.charAt(i) - '0';
                i--;
            }
            if(j >= 0) {
                sum += b.charAt(j) - '0';
                j--;
            }

            carrier[0] = sum / 10;
            sb.append(sum%10);
        }
    }
    public static void main(String args[]) {
        String res = calculate("6.91992", "4.10");
        System.out.println(res);
    }
}

I was trying to add two numbers with decimal point. However, when I print out, it was 6660f926@I[0.92002, something related to reference.

Anyone knows how to fix it?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

1

You have a typo in your code. You appended the array itself, rather than the desired element of the array, so you've built yourself a String that literally contains the hashcode of your carrier array.

The line:

sb.append(carrier);

should be:

sb.append(carrier[0]);

Just FYI, what you believe to be a reference is actually the hashcode of the value of the field carrier.

MarsAtomic
  • 10,436
  • 5
  • 35
  • 56