Question

I need help with this Java problem, please. Code must be written in Java Create an...

I need help with this Java problem, please. Code must be written in Java

Create an application that calculates batting statistics for baseball players.

Console

Welcome to the Batting Average Calculator

Enter number of times at bat: 5

0 = out, 1 = single, 2 = double, 3 = triple, 4 = home run

Result for at-bat 1: 0

Result for at-bat 2: 1

Result for at-bat 3: 0

Result for at-bat 4: 2

Result for at-bat 5: 3

Batting average: 0.600

Slugging percent: 1.200

Another player? (y/n): y

Enter number of times at bat: 3

0 = out, 1 = single, 2 = double, 3 = triple, 4 = home run

Result for at-bat 1: 0

Result for at-bat 2: 4

Result for at-bat 3: 0

Batting average: 0.333

Slugging percent: 1.333

Anotherplayer? (y/n): n

Bye!

Specifications

The batting average is the total number of at bats for which the player earned at least one base divided by the number of at bats.

The slugging percentage is the total number of bases earned divided by the number of at bats.

Use an array to store the at-bat results for each player.

Validate the input like this:

  • For number of at bats, the user must enter an integer from 1 to 30.
  • For each at bat, the user must enter 0, 1, 2, 3, or 4.

Format the batting average and slugging percent to show three decimal digits.

Calculate the statistics for another player only if the user enters 'y' or 'Y' at the 'Another player?' prompt. Otherwise, end the application.

Criteria

Acquire at-bat count Prompt for and allow the user to enter a batter's number of times at bat.

Acquire each at-bat result Prompt for and allow the user to enter a batter's result for each time at bat.

This criterion is linked to a Learning OutcomeValidate at-bat count. Validate the input so that for the number of at-bats, the user must enter an integer from 1 to 30

This criterion is linked to a Learning OutcomeValidate at-bat count. Validate the input so that for each at-bat, the user must enter 0, 1, 2, 3, or 4.

This criterion is linked to a Learning OutcomeCalculate statistics. The batting average is the total number of at-bats for which the player earned at least one base divided by the number of at-bats. The slugging percentage is the total number of bases earned divided by the number of at-bats.

Format statistics Format the batting average and slugging percentages to show three decimal digits.

Continue on Yes response only. Calculate the statistics for another player only if the user enters 'y' or 'Y' at the 'Another player?' prompt. Otherwise, end the application.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the code in java for "Batting Average Calculator" below:

import java.io.*;

public class BattingAverageCalculator {
   public static void main(String[] args) throws IOException {
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       String anotherPlayer = "y";
      
       /*
       * This loop continues only if anotherPlayer = y or Y
       */
       while(anotherPlayer.equalsIgnoreCase("y")) {
           int numAtBats;               // Variable to store the value of "Number of times at bat"
           /*
           * Getting the value for "Number of times at-bat"
           * This loop continues until a value between 1 and 30 is entered
           * (For number of at bats, the user must enter an integer from 1 to 30.)
           */
           while(true) {
               System.out.print("Enter number of times at bat: ");
               numAtBats = Integer.parseInt(br.readLine());
               if(numAtBats >= 1 && numAtBats <= 30) {           // Validating the number of at-bats entered
                   break;
               }
               else {
                   System.out.println("Please enter an integer between 1 (inclusive) and 30 (inclusive).");
               }
           }
          
           int[] atBat = new int[numAtBats];       // Array to store the at-bat results
           System.out.println("0 = out, 1 = single, 2 = double, 3 = triple, 4 = home run");
          
           /*
           * Getting the values for each at-bat
           */
           for(int i=0;i<numAtBats;i++) {
               /*
               * This while loop continues until a value between 0 and 4 is entered for each at-bat
               * (For each at bat, the user must enter 0, 1, 2, 3, or 4.)
               */
               while(true) {
                   System.out.print("Result for at-bat " + (i + 1) + ": ");
                   int val = Integer.parseInt(br.readLine());
                   if(val >= 0 && val <= 4) {           // Validating the at-bat value entered
                       atBat[i] = val;
                       break;
                   }
                   else {
                       System.out.println("Please enter an integer between 0 (inclusive) and 4 (inclusive).");
                   }
               }
           }
          
           /*
           * Calculating Batting average and Slugging percent
           */
           int numAtleastBaseSum = 0;
           int numBaseSum = 0;
           for(int i=0;i<numAtBats;i++) {
               if(atBat[i] > 0) {
                   numAtleastBaseSum ++;       // Calculating the number of at-bats with atleast one base
               }
               numBaseSum += atBat[i];           // Calculating the number of bases earned
           }
          
           Double batAvg = Double.valueOf(numAtleastBaseSum) / Double.valueOf(numAtBats);   // No. of at-bats with atleast one base (numAtleastBaseSum) / No. of at-bats (numAtBats)
           Double slugPercent = Double.valueOf(numBaseSum) / Double.valueOf(numAtBats);   // No. of bases earned (numBaseSum) / No. of at-bats (numAtBats)
           System.out.println("Batting average: " + String.format("%.3f", batAvg));       // Formatting the batting average to 3 decimal places and displaying
           System.out.println("Slugging percent: " + String.format("%.3f", slugPercent));   // Formatting the slugging percent to 3 decimal places and displaying
          
           System.out.print("Another player? (y/n): ");                                   // Asking if the user wants to continue with another player
           anotherPlayer = br.readLine();
       }
   }
}

Below are the screenshots for the code:

Below is the screenshot of the console output:

Hope this would suffice your requirement and also hoping for a positive review.

Add a comment
Know the answer?
Add Answer to:
I need help with this Java problem, please. Code must be written in Java Create an...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Need help writing this code in python. This what I have so far. def display_menu(): print("======================================================================")...

    Need help writing this code in python. This what I have so far. def display_menu(): print("======================================================================") print(" Baseball Team Manager") print("MENU OPTIONS") print("1 - Calculate batting average") print("2 - Exit program") print("=====================================================================")    def convert_bat(): option = int(input("Menu option: ")) while option!=2: if option ==1: print("Calculate batting average...") num_at_bats = int(input("Enter official number of at bats: ")) num_hits = int(input("Enter number of hits: ")) average = num_hits/num_at_bats print("batting average: ", average) elif option !=1 and option !=2: print("Not a valid...

  • Using the random dumber library in c++ please help me out with this problem. I am...

    Using the random dumber library in c++ please help me out with this problem. I am suppose to simulate at the bat using the information given. Out Walk 9.7% Single 22.0% Double 6.1% Triple 2.5% Home Run 1.7% 58.0% Based on the above percentages, write a program to simulate Casey stepping up to the plate 1000 times and count and display the number of outs, walks, singles and so on. Then calculate and display his batting average: number of hits...

  • Option #1: Batting The batting average of a baseball player is the number of “hits” divided by the number of “at-bats.”...

    Option #1: Batting The batting average of a baseball player is the number of “hits” divided by the number of “at-bats.” Recently, a certain major league player’s at-bats and corresponding hits were recorded for 200 consecutive games. The consecutive games span more than one season. Since each game is different, the number of at-bats and hits both vary. For this particular player, there were from zero to five at-bats. Thus, one can sort the 200 games into six categories: 0...

  • Can you please Test and debug the program below using the following specifications? Many thanks! Create...

    Can you please Test and debug the program below using the following specifications? Many thanks! Create a list of valid entries and the correct results for each set of entries. Then, make sure that the results are correct when you test with these entries. Create a list of invalid entries. These should include entries that test the limits of the allowable values. Then, handle the invalid integers (such as negative integers and unreasonably large integers). In addition, make sure the...

  • Help me figure this problem out, please. Use a list to store the players Update the...

    Help me figure this problem out, please. Use a list to store the players Update the program so that it allows you to store the players for the starting lineup. This should include the player’s name, position, at bats, and hits. In addition, the program should calculate the player’s batting average from at bats and hits. Console ================================================================ Baseball Team Manager MENU OPTIONS 1 – Display lineup 2 – Add player 3 – Remove player 4 – Move player 5...

  • I need a code summary for these problems Sale Total Create a Visual C# Windows Console...

    I need a code summary for these problems Sale Total Create a Visual C# Windows Console Application that will prompt the user to enter what type of item they are purchasing, the quantity of the item, and the price for the item. Calculate the subtotal, the sales tax and the sales total (subtotal + sales tax) and output all 3 to the user. Assume that the sales tax for your application is 8.5% (create a constant to store this value...

  • The batting average of a baseball player is the number of “hits” divided by the number of “at-bats.” Recently, a certain...

    The batting average of a baseball player is the number of “hits” divided by the number of “at-bats.” Recently, a certain major league player’s at-bats and corresponding hits were recorded for 200 consecutive games. The consecutive games span more than one season. Since each game is different, the number of at-bats and hits both vary. For this particular player, there were from zero to five at-bats. Thus, one can sort the 200 games into six categories: 0 at-bats 1 at-bat...

  • need done in java An experiment was conducted and resulted in a series of pH measurements....

    need done in java An experiment was conducted and resulted in a series of pH measurements. The number of samples is known ahead of time. Have your program prompt the user to enter that number of measurements. Validate the number to ensure it's in the range of 2 to 100 measurements, inclusive. If it is out range, display an error message, Error: valid range is 2 to 100 If it's within the range, then use the number of measurements to...

  • Step 4: Add code that discards any extra entries at the propmt that asks if you...

    Step 4: Add code that discards any extra entries at the propmt that asks if you want to enter another score. Notes from professor: For Step 4, add a loop that will validate the response for the prompt question:       "Enter another test score? (y/n): " This loop must only accept the single letters of ‘y’ or ‘n’ (upper case is okay). I suggest that you put this loop inside the loop that already determines if the program should collect...

  • This is a matlab HW that I need the code for, if someone could help me figure this out it would b...

    This is a matlab HW that I need the code for, if someone could help me figure this out it would be appreciated. The value of t can be estimated from the following equation: in your script file, estimate the value of π for any number of terms. You must ask the user for the desired number of terms and calculate the absolute error/difference between your calculation and the built-in MATLAB value ofpi. Display your results with the following message...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT