Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170629;
- import java.util.Random;
- import java.util.Scanner;
- public class arrayHistogram {
- public static void main(String[] args) {
- /*
- * histogram
- * input: grades of students. until the first invalid grade
- * output: the number of grades, and a histogram of grades
- */
- // create a scanner
- Scanner s = new Scanner(System.in);
- // array for counting grades
- // 0 for 0-9, 1 for 10-19, ... , 9 for 90-99, 10 for 100
- int[] count = new int[11];
- for (int i = 0; i < count.length; i += 1) {
- count[i] = 0; // initialize counter
- }
- int total = 0; // total number of students
- // data source
- char dataSource; // auto=computer or manual=user;
- do {
- System.out
- .println("select data source ('m' for manual, 'a' for auto): ");
- dataSource = s.next().charAt(0);
- } while (dataSource != 'a' && dataSource != 'A' && dataSource != 'm'
- && dataSource != 'M');
- if (dataSource == 'a' || dataSource == 'A') {
- // computer select number of students and their grades
- Random rnd = new Random();
- total = 20 + rnd.nextInt(980); // number of students: 20 to 999
- for (int i = 0; i < total; i += 1) {
- int grade = rnd.nextInt(101); // get random grade
- count[grade / 10] += 1; // update counter
- }
- } else {
- // read grades from the user
- System.out
- .println("Enter grades of students (1 to 100), or any other number to exit: ");
- do {
- int grade = s.nextInt();
- // if invalid grade
- if (grade < 0 || grade > 100) {
- // then stop
- break;
- }
- // else
- count[grade / 10] += 1;
- total += 1;
- } while (true);
- s.close();
- }
- // printing results
- System.out.println("distribution of the grades:");
- System.out.println("+-----------+-----+--------+");
- System.out.println("| Range | No. | % |");
- System.out.println("+-----------+-----+--------+");
- for (int i = 0; i < count.length; i += 1) {
- int rangeFrom = 10 * i;
- int rangeTo = i == 10 ? 10 * i : 10 * (i + 1) - 1;
- double percent = 100 * count[i] / (double) total;
- System.out.printf("| %3d - %3d | %3d | %6.2f |\n", rangeFrom,
- rangeTo, count[i], percent);
- System.out.println("+-----------+-----+--------+");
- }
- System.out.printf("Total number of students is %d\n", total);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement