Question

In: Computer Science

Write an application that allows a user to enter any number of student quiz scores until...

Write an application that allows a user to enter any number of student quiz scores until the user enters 99. If the score entered is less than 0 or more than 10, display an appropriate message and do not use the score. After all the scores have been entered, display the number of scores entered, the highest score, the lowest score, and the arithmetic average. Save the file as QuizScoreStatistics.java.


I am struggling with looping in Java and do not understand how to go about it. Could someone help answer this and place cmments in the code?

Solutions

Expert Solution

import java.util.*; 

class Main {
public static void main(String[] args) {
    // We will use ArrayLists to store the data we have since the size of the data is not known. 
    ArrayList<Integer> marks = new ArrayList<Integer>(); 
    // We need a scanner object to get the input values from the user. 
    Scanner myObj = new Scanner(System.in);
    // This is a special loop used when the data is not known beforehand - that is, we do not know 
    // whether it's 10 or 100 values that are going to be stored. Hence, we use a while(true) loop 
    // And then we use a break statement on the condition that the input value is 99 as desired in the 
    // question. 
    while(true) {
    // we get the grades from the user 
      int grade = myObj.nextInt();
    // if it is a 99 value we need to terminate the loop - we use a "break" statement. 
      if(grade == 99) break;
    // When the grade entered does not match the condition of being between 0 and 10
    // We keep the loop running by terminating this instance of a loop 
    // and keeping the loop running anyway. We use a continue statement to accomplish this.  
      if(grade < 0 || grade > 10) {
        System.out.println("You have entered incorrect grade. Try again.");
        continue; 
      }
     // if the grade is a legal value we add it to the ArrayList 
      marks.add(grade);
    }
   // Now we get to the output statements. 
    System.out.print("You have entered data for ");
    System.out.print(marks.size());
    System.out.print(" students. \n");
   // We have not yet calculated the maximum and minimum values, we use for loops to accomplish this. 
   // If we encounter any value larger than the defined max_val, we update the max_val to that value. 
   // The reverse logic is applied for the min_val. 
   // Meanwhile we use a variable sum to keep track of the sum of all the elements so far. 
   // This is necessary to compute the average. 
    int max_val = marks.get(0);
    int min_val = marks.get(0); 
    int sum = 0; 
    for (int i = 0; i < marks.size(); i++) {
      if(marks.get(i) > max_val) max_val = marks.get(i); 
      if(marks.get(i) < min_val) min_val = marks.get(i);
      sum += marks.get(i);
    } 
    // Now we can compute the average since we have the sum of all elements as well as the 
    // total number of elements in the ArrayList. We get: 
    float avg = (int) sum/marks.size();
    System.out.print("The minimum score is ");
    System.out.print(min_val);
    System.out.print("\n");

    System.out.print("The maximum score is ");
    System.out.print(max_val);
    System.out.print("\n");

    System.out.print("The average score is ");
    System.out.print(avg);
    System.out.print("\n"); 
    
   // We now close the scanner to avoid resource leaks. 
    myObj.close();
  }
}

We have used ArrayList as the data structure to keep track of all the incoming values since we do not know the size beforehand (the user may enter as many values as they desire). The code has been commented with all the information necessary to understand the working of the code. A note:

This kind of program (where the user terminates and that decides the number of elements we need to store) requires a while(true) kind of looping structure. Here, we could have an arbitrarily large termination of a for loop, but this is a much more efficient way of achieving the same thing. We do not need to arbitrarily guess what would be the maximum number of iterations in this case. The break statement can terminate the loop whenever the desired condition is satisfied - in this case, that condition is satisfied when the value of the user input hits 99. Then we break out of the loop.

Another tricky usage here is of the continue statement - here, we notice that having one negative value or value greater than 10 does not mean we need to terminate the program, we merely need to skip it. Hence, again making use of the while(true) looping mechanism, we simply add a continue statement here so that the program can simply display an error message but continue executing anyway.

A sample run of the code here:

(If you liked this answer, feel free to give it a thumbs up. Thank you so much!)


Related Solutions

Write an application that allows a user to enter any number of student quiz scores, as...
Write an application that allows a user to enter any number of student quiz scores, as integers, until the user enters 99. If the score entered is less than 0 or more than 10, display Score must be between 10 and 0 and do not use the score. After all the scores have been entered, display the number of valid scores entered, the highest score, the lowest score, and the arithmetic average.
Write an application that allows a user to enter the names and birthdates of up to...
Write an application that allows a user to enter the names and birthdates of up to 10 friends. Continue to prompt the user for names and birthdates until the user enters the sentinel value ZZZ for a name or has entered 10 names, whichever comes first. When the user is finished entering names, produce a count of how many names were entered, and then display the names. In a loop, continuously ask the user to type one of the names...
Show: Create an application that allows the user to enter the number of calories and fat...
Show: Create an application that allows the user to enter the number of calories and fat grams in a food. The application should display the percentage of the calories that come from fat. If the calories from fat are less than 30% of the total calories of the food, it should also display a message indicating the food is low in fat. One gram of fat has 9 calories, so: Calories from fat = fat grams *9 The percentage of...
Write a program that runs on SPIM that allows the user to enter the number of...
Write a program that runs on SPIM that allows the user to enter the number of hours, minutes and seconds and then prints out the total time in seconds. Name the source code file “seconds.asm
Write a program that runs on SPIM that allows the user to enter the number of...
Write a program that runs on SPIM that allows the user to enter the number of hours, minutes and seconds and then prints out the total time in seconds. Name the source code file “seconds.asm Explain step by step
In Java: Write a program that prompts the user to enter a positive number until the...
In Java: Write a program that prompts the user to enter a positive number until the user input a negative number. In the end, the program outputs the sum of all the positive numbers. You should use do-while loop (not while, not for). You cannot use break or if statement in the lab. Hint: if the program adds the last negative number to your sum, you can subtract the last number from the sum after the loop.
Write a C++ console application that allows your user to enter the total rainfall for each...
Write a C++ console application that allows your user to enter the total rainfall for each of 12 months into an array of doubles. The program should validate user input by guarding against rainfall values that are less than zero. After all 12 entries have been made, the program should calculate and display the total rainfall for the year, the average monthly rainfall, and the months with the highest and lowest rainfall amounts.
In Python, write a program that allows the user to enter a number between 1-5 and...
In Python, write a program that allows the user to enter a number between 1-5 and returns the vitamins benefits based on what the user entered. The program should: Continue to run until the user quits and Validate the user’s input (the only acceptable input is 0, 1, 2, 3, 4, or 5), If the user enters zero “0” the program should terminate You can use the following facts: 1- Vitamin A protects eyes from night blindness and age-related decline...
In Python, write a program that allows the user to enter a number between 1-5 and...
In Python, write a program that allows the user to enter a number between 1-5 and returns the vitamins benefits based on what the user entered. The program should: Continue to run until the user quits and Validate the user’s input (the only acceptable input is 0, 1, 2, 3, 4, or 5), If the user enters zero “0” the program should terminate You can use the following facts: 1- Vitamin A protects eyes from night blindness and age-related decline...
Using Visual Studio write a program that allows the user to enter multiple scores ranging from...
Using Visual Studio write a program that allows the user to enter multiple scores ranging from 0 to 100, computes the average of those scores and then writes out a letter grade using the typical grading scale. Your program will also: 1. Allow the user to enter any number of scores he or she wishes but assume there will be at least one score entered. 2. Use a sentinel-controlled loop variable to terminate the loop when the user has no...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT