Question

i try to print values into a file but my results are cutted when longer then 4 digits:

import java.io.FileNotFoundException;
import java.math.BigInteger;

public class create_referencevalues {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Long[] list = { 10L, 40L, 90L, 160L, 250L, 350L, 500L, 650L, 800L,
                1000L };

        try {
            java.io.PrintStream p = new java.io.PrintStream(
                    new java.io.BufferedOutputStream(
                            new java.io.FileOutputStream(new java.io.File(
                                    "C:/users/djdeejay/listall.csv"), false)));
            for (long i = 0; i < 1024; i++) {
                //p.print(Long.toBinaryString(i));
                Long sum1 = 0L;
                for (int j = 0; j < 10; j++) {
                    if (BigInteger.valueOf(i).testBit(j)) {
                        sum1 += (list[j]);
                    }
                }

                p.println( i + ";"+sum1);

            }

            p.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

Here are the 5 last values as printed:

1018;3750
1019;3760
1020;3800
1021;3810
1022;3840
1023;3850

last should be: 38500

what do I miss here ???

Was it helpful?

Solution

There is nothing wrong with the println. Your code does exactly what I'd expect it to do. Consider the last line, which you claim isn't correct:

1023;3850

The decimal 1023 is 1111111111 in binary. Therefore when i=1023, the inner loop of your program would simply compute the sum of all numbers in list. These numbers add up to 3850, which is what gets printed.

OTHER TIPS

The last one should actually be 3850 and not 38500. When i = 1023 all bits are set and the last line will be the same as if you add all numbers in list[] together.

1000+650+800+500+350+250+160+90+40+10 = 3850

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