I'm taking a beginner Java class, with the assignment to create a histogram program with the following output: (100 and 10 are user inputs).
How many numbers? 100 How many intervals? 10
Histogram
--------------------------------------------------------
1 ****(4)
2 ******(6)
3 ***********(11)
4 *****************(17)
5 **************************(26)
6 *************************(25)
7 *******(7)
8 ***(3)
9 (0)
10 *(1)
--------------------------------------------------------
My code is giving the following output however, can anyone help me point out what is going wrong, thanks so much.
How Many Numbers? 10
How Many Intervals? 10
Histogram
--------------------------------------------------------
1 **********(10)
2 **********(10)
3 **********(10)
4 **********(10)
5 **********(10)
6 **********(10)
7 **********(10)
8 **********(10)
9 **********(10)
10 **********(10)
For the input, 100 and 10 I get the error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at Lab6.main(Lab6.java:44) I marked Line 44 below.
Which links to this code; intervalValue[j]++;
I'm not sure how to attach the generator (.jar) file, it is supposed to just generate the random #'s for us. Thanks again.
mport java.util.Scanner;
public class Lab6 {
public static void main(String[] args) {
int numbers, intervals;
double intervalWidth;
double max, mins, range;
Scanner keyboard = new Scanner(System.in);
System.out.print("How Many Numbers? ");
numbers = keyboard.nextInt();
System.out.print("How Many Intervals? ");
intervals = keyboard.nextInt();
double [] generate = new double[numbers];
generate = randomGenerator(numbers);
max = maximum(generate);
mins = minimum(generate);
range = max - mins;
intervalWidth = range / intervals;
int [] intervalValue = new int[intervals];
for (int i=0; i < generate.length; i++) {
for (int j = 0; j<generate.length; j++){
double imin = mins+j*intervalWidth;
double imax = max +j*(intervalWidth);
if(generate[i] >= imin && generate[i] < imax)
intervalValue[j]++; //LINE 44
}
}
System.out.println("Histogram");
System.out.println("--------------------------------" +
"------------------------");
for (int a=0; a < intervalValue.length; a++) {
System.out.print(" " + (a+1) + " ");
for (int b=0; b < intervalValue[a]; b++) {
System.out.print("*");
}
System.out.println("(" + intervalValue[a] + ")");
}
}
private static double [] randomGenerator(int number) {
double [] generate;
generate = Generator.getData(number);
return generate;
}
private static double maximum(double [] a) {
double max = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] > max) {
max = a[i];
}
}
return max;
}
private static double minimum(double [] a) {
double mins = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < mins) {
mins = a[i];
}
}
return mins;
}
}