QUOTE(Runesmith @ 2 Apr, 2008 - 08:44 PM)

I tried Locke's solution, but I keep getting an "exception" error a second or so after I try to run it. No errors are popping up on my compiler, though. Here's the code I'm using:
CODE
package array;
/**
*
* @author Runesmith
*/
public class Main {
public static void main(String[] args) {
int[] count = new int[10];
int num;
for(int i = 0; i < 10; i++){
num = (int)Math.random() * 10;
switch(num){
case 0:
count[0]++;
break;
case 1:
count[1]++;
break;
.........
case 8:
count[8]++;
break;
case 9:
count[9]++;
break;
case 10:
count[10]++;
break;
}
for (int x = 0; x <= 10; x++)
System.out.println(count[x]);
}
}
}
I also tried to use the other code segments, but none of them worked at all. I'm probably just putting the code in the wrong spot, though...
Your variable count is int count[10]
So there are count[0], count[1], .... count[8], count[9]
doing
CODE
for (int x = 0; x <= 10; x++)
System.out.println(count[x]);
will try to access count[10]
you should do
CODE
for (int x = 0; x < 10; x++)
System.out.println(count[x]);
or even better
CODE
for (int x = 0; x < count.length; x++)
System.out.println(count[x]);
another problem is that Math.random() return a numeber betwwen 0.0 et 0.1
so you will have
0.000001, 0.0083, 0.00765, ......
multiplying the numbers by 10 will still get you 0 and count[0] will have a count of probably 10
Better to use a Random object that will return and int between 0 and the parameter:
(and as prevoiusly suggested get ride of the useless switch statement what will you do if you want numbers between 0 and 1000 ?)
so:
java
public class Main {
public static void main(String[] args) {
int[] count = new int[10];
int num;
Random random = new Random();
for(int i = 0; i < 10; i++){
// get random number betwween 0 (inclusive) and 10 (exclusive)
num = random.nextInt(10);
count[num]++;
}
for (int x = 0; x < 10; x++)
System.out.println(x + ") " + count[x]);
This post has been edited by pbl: 3 Apr, 2008 - 03:23 AM