fork download
  1. class StudentPoll { // Define the class named StudentPoll
  2. public static void main(String[] args) { // Main method where execution starts
  3.  
  4. int[] response = {1, 2, 4, 3, 2, 1, 1, 3, 14, 4, 2}; // Array of student responses (some valid 1-5, one invalid 14)
  5.  
  6. int[] frequency = new int[6]; // Create array to hold frequency counts for ratings 1 to 5 (index 1 to 5 used)
  7.  
  8. for (int answer = 0; answer < response.length; answer++) { // Loop through each response
  9. try {
  10. ++frequency[response[answer]]; // Try to increment count at index equal to response value
  11. } catch (ArrayIndexOutOfBoundsException e) { // Catch error if response is out of valid range (i.e., > 5 or < 0)
  12. System.out.printf("Exception: %s\n", e); // Print the exception details
  13. System.out.printf("response[%d] = %d\n\n", answer, response[answer]); // Print index and invalid value
  14. }
  15. }
  16.  
  17. System.out.printf("%s%10s\n", "Rating", "Frequency"); // Print table header
  18. for (int rating = 1; rating < frequency.length; rating++) { // Loop through ratings 1 to 5
  19. System.out.printf("%6d%10d\n", rating, frequency[rating]); // Print rating and its frequency
  20. }
  21. }
  22. }
Success #stdin #stdout 0.14s 55988KB
stdin
Standard input is empty
stdout
Exception: java.lang.ArrayIndexOutOfBoundsException: Index 14 out of bounds for length 6
response[8] = 14

Rating Frequency
     1         3
     2         3
     3         2
     4         2
     5         0