1

When I run my program for a histogram, it runs, but it doesn't give the output I want. I want the output to be this, but I get this instead. If possible, I also want my histogram printed to output vertically, not horizontally. Furthermore, I would also like to add more bins.

PS: The data.txt file I have contains the following.

My code is: https://pastebin.com/VyREurFP

BigInteger range = max.toBigInteger().subtract(min.toBigInteger());
        BigInteger maxWidth = new BigInteger("8");
        BigInteger width = new BigInteger("1");
        if (range.compareTo(maxWidth) == 1){
            width = range.divide(maxWidth);
            if (range.remainder(maxWidth).compareTo(BigInteger.ZERO)==1){
                width = width.add(BigInteger.ONE);
            }
        }
        int binCount = range.divide(width).intValue();
        if (range.remainder(width).compareTo(BigInteger.ZERO)==1){
            binCount++;
        }
        // binCount is the number of bins that will be used
        // Find the class interval for each bin
        List<String> classInterval = new ArrayList<>();
        BigInteger classStart = min.toBigInteger();
        for (int b = 0; b< binCount; b++){
            classInterval.add(String.format("%3s",classStart.toString())+" >= x < "+String.format("%3s",classStart.add(width).toString()));
            classStart = classStart.add(width);
        }
        // Fill each bin
        long[] bin = new long[binCount];
        BigDecimal bw = new BigDecimal(width);
        for (int i = 0; i< list.size(); i++){
            int binNumber = list.get(i).divide(bw,RoundingMode.HALF_UP).intValue()-1;
            bin[binNumber]++;
        }
        // Print out the details of each bin
        int total = 0;
        for (int b = 0; b< binCount; b++){
            System.out.print(classInterval.get(b)+" |");
            for (int d = 0; d<total; d++){
                System.out.print("#");
            }
            for (int v = 0; v< bin[b]; v++){
                System.out.print("*");
                total++;
            }
            for (long s = bin[b]; s<60;s++){
                System.out.print(" ");
            }
            System.out.println("("+bin[b]+")");
        }
georg
  • 211,518
  • 52
  • 313
  • 390
  • Have a look at the `Formatter` class (and the accompanying `String#format` method). They would make this into a one-liner. – Rogue Nov 24 '19 at 16:39

0 Answers0