This program is supposed to print out the number of times each number has been generated of 100 random numbers in the scale of 1 to 10 (then put it in the array).
I can't think of any other way than to have an if-statement for each number. Is there any way to avoid so many if statements by another code or something?
public static void countNumbers() {
Random generator = new Random();
int arr[] = new int[101];
int add[] = new int[10];
for (int i = 0; i < 100; i++) {
int sum = 0;
arr[i] = generator.nextInt(10)+1;
if(arr[i] ==1){
add[0]++;
}
if(arr[i] ==2){
add[1]++;
}
if(arr[i] ==3){
add[2]++;
}
if(arr[i] ==4){
add[3]++;
}
if(arr[i] ==5){
add[4]++;
}
if(arr[i] ==6){
add[5]++;
}
if(arr[i] ==7){
add[6]++;
}
if(arr[i] ==8){
add[7]++;
}
if(arr[i] ==9){
add[8]++;
}
if(arr[i] ==10){
add[9]++;
}
}
System.out.println(Arrays.toString(add));
System.out.println();
}
Aucun commentaire:
Enregistrer un commentaire