Generating Integers and Checking the Count of Each in Java

Problem:

(Counting single digits) Write a program that generates one hundred random integers between 0 and 9 and displays the count for each number. Hint: Use (int)(Math.random() * 10) to generate a random integer between 0 and 9. Use an array of ten integers, say counts, to store the counts for the number of 0's, 1's, ..., 9's.


Solution:

public class RandomNumbers {
 
 public static void main(String[] args) {
  int[] frequency = new int[10];
  
  for(int i = 0; i < 100; i++){
   int randomNumber = generate();
   frequency[randomNumber]++;
  }
  
  printArray(frequency);
 }
 
 private static int generate(){
  return (int)(Math.random() * 10);
 }
 
 private static void printArray(int[] array){
  for(int i = 0, size = array.length; i < size; i++ ){
   System.out.println(i + " frequence -> " + array[i]);
  }
 }
 
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact