Created
January 4, 2016 17:55
-
-
Save gulzaar/262a3cbc45f29105238e to your computer and use it in GitHub Desktop.
Student Poll Calculation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Fig. 7.8: StudentPoll.java | |
// Poll analysis program. | |
public class StudentPoll { | |
public static void main( String[] args ) { | |
// student response array (more typically, input at runtime) | |
int[] responses = { 1, 2, 5, 4, 3, 5, 2, 1, 3, 3, 1, 4, 3, 3, 3, 2, 3, 3, 2, 14 }; | |
int[] frequency = new int[ 6 ]; // array of frequency counters | |
// for each answer, select responses element and use that value | |
// as frequency index to determine element to increment | |
for ( int answer = 0; answer < responses.length; answer++ ) { | |
try { | |
++frequency[ responses[ answer ] ]; | |
} // end try | |
catch ( ArrayIndexOutOfBoundsException e ) { | |
System.out.println( e ); | |
System.out.printf( " responses[%d] = %d\n\n", answer, responses[ answer ] ); | |
} // end catch | |
} // end for | |
System.out.printf( "%s%10s\n", "Rating", "Frequency" ); | |
// output each array element's value | |
for ( int rating = 1; rating < frequency.length; rating++ ) | |
System.out.printf( "%6d%10d\n", rating, frequency[ rating ] ); | |
} // end main | |
} // end class StudentPoll | |
/* | |
java.lang.ArrayIndexOutOfBoundsException: 14 | |
responses[19] = 14 | |
Rating Frequency | |
1 3 | |
2 4 | |
3 8 | |
4 2 | |
5 2 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment