Thanks everybody! I cleaned up the code to the best of my knowledge and decided to paste the completed code along with a sample output for other students to see and if they choose to use parts of the code.
public class Arrays {
public static void main(String args[]) {
//Assigning the array length according to the user's input
int N = Integer.parseInt(args[0]);
int randoms[] = new int[N];
//Filling the array with random integer values
System.out.println("The numbers generated are: ");
for (int i=0; i<randoms.length; i++) {
randoms[i] = (int) (Math.random()*10 + 1);
System.out.print(randoms[i] + " ");
}
double sum = 0.0;
for (int i=0; i<randoms.length; i++) {
sum += randoms[i];
}
System.out.println("\nThe average of the values is " + (sum/N));
int freq[] = new int[11];
for (int i=0; i<randoms.length; i++){
freq[randoms[i]] += 1;
}
System.out.println("Number\tFreq");
for (int i=1; i<freq.length; i++){
System.out.println(i + "\t" + freq[i]);
}
}
}
Sample Output:
> java Arrays 15
The numbers generated are:
4 8 1 10 6 7 8 4 6 6 3 4 4 5 8
The average of the values is 5.6
Number Freq
1 1
2 0
3 1
4 4
5 1
6 3
7 1
8 3
9 0
10 1
As Adrian pointed out you're currently only counting ones. I would be a bit tricky and instead of doing a check on each one, simply using the random integer to select the correct element for increment
for (int i=0; i<randoms.length; i++){
freq[randoms[i]-1] += 1;
}
Thanks for the help! After looking at the code long enough I realized that in my output i was using
for (int i=0; i<randoms.length; i++){
System.out.println(randoms[i] + " appeared " + freq[i] + " times");
When I should have used
for (int i=0; i<randoms.length; i++){
System.out.println(randoms[i] + " appeared " + freq[randoms[i]] + " times");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.