Francis Velez
Francis Velez

Reputation: 19

Creating a histogram with given values using arrays help pls :(

We were asked to create a simple histogram with a given values but my code seems not working. i really need help on this one. EDIT:This error shows up when im running it:

(Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5` at Exercise39_Histogram.main(Exercise39_Histogram.java:13) Process completed)

Code:

 public class Exercise39_Histogram
    {
        public static void main(String args[])
        {
            int el[]= new int[]{0, 1, 2, 3, 4, 5};
            int val[] = new int[]{10, 3, 6, 18, 11, 1};
            String ast[] = new String[5];
            ast[0] = "**********";
            ast[1] = "***";
            ast[2] = "******";
            ast[3] = "******************";
            ast[4] = "***********";
            ast[5] = "*";

            System.out.println("Elements\tValue\tHistogram");
            System.out.print(el[0]+"\t"+val[0]+"\t"+ast[0]);
            System.out.print(el[1]+"\t"+val[1]+"\t"+ast[1]);
            System.out.print(el[2]+"\t"+val[2]+"\t"+ast[2]);
            System.out.print(el[3]+"\t"+val[3]+"\t"+ast[3]);
            System.out.print(el[4]+"\t"+val[4]+"\t"+ast[4]);
            System.out.print(el[5]+"\t"+val[5]+"\t"+ast[5]);

            }   
    }

Upvotes: 0

Views: 73

Answers (2)

user3437460
user3437460

Reputation: 17454

This error shows up when im running it: (Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Exercise39_Histogram.main(Exercise39_Histogram.java:13) Process completed)

You are getting this exception because ast[5] doesn't exist.

Remember that the index of an array starts from 0, and not 1.

So by doing String ast[] = new String[5];, you are creating an array of size 5, which means you only space for 5 elements:

ast[0]
ast[1]
ast[2]
ast[3]
ast[4]

Your code ast[5] = "*"; at line 13 is trying to access the 6th element which doesn't exist and thus giving you ArrayIndexOutOfBounsException.


As for your print out, you may want to use a loop:

System.out.println("Elements\tValue\tHistogram");
for(int x=0; x<6; x++)
    System.out.println(el[x]+"\t"+val[x]+"\t"+ast[x]);

Upvotes: 0

Jure
Jure

Reputation: 799

When you create your array you set it's size to 5,

String ast[] = new String[5];

but latter when you use

ast[5] = "*";

you trying to save data witch has index 6, since array index starts with 0. You should change size of your array to 6.

And to get correct display, you would probably want to use:

System.out.println

for all histograms displayed, or else they will all be displayed in same row.

Upvotes: 3

Related Questions