Pages

Saturday, 20 August 2016

Chapter 7 Exercise 7, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.


*7.7 (Count single digits) Write a program that generates 100 random integers between 0 and 9 and displays the count for each number. (Hint: Use an array of ten integers, say counts, to store the counts for the number of 0s, 1s, . . . , 9s.)



public class ProgrammingEx7_7 {
 
 public static void main(String[] args) {
  int[] numbers = new int[10];
   
  for (int i = 0; i < 100; i++) {
   numbers[intRandom(0, 9)]++;
  }
   
   
  for (int i = 0; i < numbers.length; i++) {
   System.out.println("Number " + i + " appears " + numbers[i] + " times." );
    
  }
 
 }
  
  
 public static int intRandom(int lowerBound, int upperBound) {
  return (int) (lowerBound + Math.random()
    * (upperBound - lowerBound + 1));
 }
 
}

No comments:

Post a Comment