Question

Write a Java program that Reads baseball data in from a comma delimited file. Each line...

Write a Java program that Reads baseball data in from a comma delimited file. Each line of the file contains a name followed by a list of symbols indicating the result of each at bat: 1 for single, 2 for double, 3 for triple, 4 for home run, o for out, w for walk, s for sacrifice

Statistics are computed and printed for each player.

EXTRA CREDIT (+10 points); compute each player's slugging percentage https://www.wikihow.com/Calculate-Slugging-Percentage

Be sure to avoid a division by zero error

Use the starting code I provide here. Also use the files stats.txt and stats2.txt for test files.

*CODE*

import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;

public class BaseballStats {

public static void main (String[] args) throws IOException {

   Scanner fileScan, lineScan;
   String fileName;
   String line; //a line from the file
   String playerName;
   int numHits, numWalks, numSacrifices, numOuts;
   String action;

   Scanner scan = new Scanner (System.in);

   System.out.print ("Enter the name of the input file: ");
   fileName = scan.nextLine();
   fileScan = new Scanner (new File(fileName));

   // Read and process each line of the file
   while (fileScan.hasNext()) {
       line = fileScan.nextLine();
       lineScan = new Scanner(line);
       lineScan.useDelimiter(",");

       numHits = 0;
       numOuts = 0;
       numSacrifices = 0;
       numWalks = 0;
       playerName = lineScan.next();

       while (lineScan.hasNext()) {
           action = lineScan.next();
           if (action.equals("1") || action.equals("2") || action.equals("3")
|| action.equals("4"))
           numHits++;
           else if (action.equals("o"))
           numOuts++;
           else if (action.equals("s"))
           numSacrifices++;
// add code to handle counting number of walks
       }

       //print statistics for the player
       System.out.println ("\nStatistics for " + playerName + "... ");
       System.out.println ("Hits: " + numHits);
       System.out.println ("Outs: " + numOuts);
       System.out.println ("Walks: " + numWalks);
       System.out.println ("Sacrifices: " + numSacrifices);

// compute total number of at bats: https://www.wikihow.com/Calculate-a-Batting-Average

// create a DecimalFormat object that limits the number of decimal digits to 3

// output the batting average BUT BE CAREFUL
// consider the situation where a batter has no at bats
// for this condition output "No at bats"
// otherwise output "Batting Average: " followed by the average formatted as specified above

// EXTRA CREDIT: compute slugging percentage and output similar to batting average

}
}
}
*STAT

Willy Wonk,o,o,1,o,o,o,o,3,w,o,o,o,o,s,1,o,4
Shari Jones,1,o,o,s,s,1,o,o,o,1,o,o,o,o
Barry Bands,2,4,w,o,o,o,w,1,o,o,1,2,o,o,w,w,w,1,o,o
Sally Slugger,o,4,4,o,o,4,4,w
Missy Lots,o,o,1,o,o,w,o,o,o
Joe Jones,o,1,o,o,o,o,1,1,o,o,o,o,w,o,o,o,1,o,1,3
Larry Loop,w,1,o,o,o,1,o,o,1,s,o,o,o,1,1
Sarah Swift,o,o,o,o,1,1,w,o,o,o
Bill Bird,1,o,3,o,1,w,o,o,o,1,s,s,2,o,o,o,o,o,o
Don Daring,o,o,3,3,o,o,3,o,3,o,o,o,o,o,o,3
Jill Jet,o,s,s,1,o,o,1,1,o,o,o,1,o,1,w,o,o,1,1,o


*STAT2

Barry Bands,4,4,w,o,o,o,w,4,o,o,4,4,o,o,w,w,w,4,o,o

Homework Answers

Answer #1

Hello Champ!

Here is the solution code in java.

Important notes :

1. Situations, that do not count as "at bats" include walks, hit-by-pitches, sacrifices, etc.

2. A batting average represents the percentage of at bats that result in hits for a particular baseball player

3. Slugging percentage represents the total number of bases a player records per at-bat. Formula for slugging percentage is: (ones*1 + twos*2 + threes*3 + fours*4)/At_bats = total_hit_score/at_bats

import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;

public class MyClass {

public static void main (String[] args) throws IOException {

   Scanner fileScan, lineScan;
   String fileName;
   String line; //a line from the file
   String playerName;
   int numHits, numWalks, numSacrifices, numOuts, hit_score_total;
   String action;

   Scanner scan = new Scanner (System.in);

   System.out.print ("Enter the name of the input file: ");
   fileName = scan.nextLine();
   fileScan = new Scanner (new File(fileName));

   // Read and process each line of the file
   while (fileScan.hasNext()) {
       line = fileScan.nextLine();
       lineScan = new Scanner(line);
       lineScan.useDelimiter(",");

       numHits = 0;
       numOuts = 0;
       numSacrifices = 0;
       numWalks = 0;
       playerName = lineScan.next();
       hit_score_total = 0; //this variable will count the total score so far

       while (lineScan.hasNext()) {
           action = lineScan.next();
           if (action.equals("1") || action.equals("2") || action.equals("3")
|| action.equals("4")){
           numHits++;
           hit_score_total += Integer.parseInt(action);
    
           }
           else if (action.equals("o"))
           numOuts++;
           else if (action.equals("s"))
           numSacrifices++;

           //Add code here to check for walks count
           else if(action.equals("w"))
           numWalks++;
       }

       //print statistics for the player
       System.out.println ("\nStatistics for " + playerName + "... ");
       System.out.println ("Hits: " + numHits);
       System.out.println ("Outs: " + numOuts);
       System.out.println ("Walks: " + numWalks);
       System.out.println ("Sacrifices: " + numSacrifices);

       // compute total number of at bats: 
       int  at_bats = numHits + numOuts;
       //at-bats does not count sacrifices and walks.
       
   
        // create a DecimalFormat object that limits the number of decimal digits to 3
        DecimalFormat df = new DecimalFormat("0.000");

        // output the batting average BUT BE CAREFUL
        // consider the situation where a batter has no at bats
        // for this condition output "No at bats"
        // otherwise output "Batting Average: " followed by the average formatted as specified above
        if(at_bats == 0){
            System.out.println("No at bats.\nNO slugging percentage.");
        }
        else{
            float batting_avg = (float)numHits/at_bats;
            System.out.println("Batting Average:"+df.format(batting_avg)); //formating and printing the batting average.
            
            // EXTRA CREDIT: compute slugging percentage and output similar to batting average
            float slugging_percentage = (float)hit_score_total/at_bats;
            System.out.println("Slugging Percent: "+df.format(slugging_percentage));
        }
    

}
}
}

OUTPUT:

Hope it help!

Know the answer?
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
Similar Questions
Hello, I am trying to create a Java program that reads a .txt file and outputs...
Hello, I am trying to create a Java program that reads a .txt file and outputs how many times the word "and" is used. I attempted modifying a code I had previously used for counting the total number of tokens, but now it is saying there is an input mismatch. Please help! My code is below: import java.util.*; import java.io.*; public class Hamlet2 { public static void main(String[] args) throws FileNotFoundException { File file = new File("hamlet.txt"); Scanner fileRead =...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The word the user is trying to guess is made up of hashtags like so " ###### " If the user guesses a letter correctly then that letter is revealed on the hashtags like so "##e##e##" If the user guesses incorrectly then it increments an int variable named count " ++count; " String guessWord(String guess,String word, String pound) In this method, you compare the character(letter)...
THIS IS A JAVA PROGRAM THAT NEEDS TO BE WRITTEN Write a recursive method void reverse(ArrayList<Object>...
THIS IS A JAVA PROGRAM THAT NEEDS TO BE WRITTEN Write a recursive method void reverse(ArrayList<Object> obj) that reverses an ArrayList of any type of object. For example, if an ArrayList held 4 strings: "hi", "hello", "howdy", and "greetings" the order would become "greetings", "howdy", "hello", and "hi". Implement a recursive solution by removing the first object, reversing the ArrayList consisting of the remaining Objects, and combining the two. Use the following class ArrayListReverser to write and test your program....
Finish the CustomerAccountTransactions program that reads customer accounts receivable data from a file and then applies...
Finish the CustomerAccountTransactions program that reads customer accounts receivable data from a file and then applies a series of transactions to the accounts. Its main() method uses the CustomerAccounts class to manage a collection of CustomerAccount objects: reading customer accounts data & transactions, and obtaining a String showing the customer accounts data after the operations are complete. You will need to complete the readCustomerAccounts () and applyTransactions() methods in the CustomerAccounts class. First, please fill in your name in the...
please write the code in java so it can run on jGRASP import java.util.Scanner; 2 import...
please write the code in java so it can run on jGRASP import java.util.Scanner; 2 import java.io.*; //This imports input and output (io) classes that we use 3 //to read and write to files. The * is the wildcard that will 4 //make all of the io classes available if I need them 5 //It saves me from having to import each io class separately. 6 /** 7 This program reads numbers from a file, calculates the 8 mean (average)...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use the file in.txt as sample input for your program. v import java.io.*; import java.util.*; public class Pretty { public static final int LINE_SIZE = 50; public static void main(String[] parms) { String inputLine; int position = 1; Scanner fileIn = new Scanner(System.in); while (fileIn.hasNextLine()) { inputLine = fileIn.nextLine(); if (inputLine.equals("")) { if (position > 1) { System.out.println(); } System.out.println(); position = 1; } else...
7.6 LAB: Exception handling to detect input String vs. Integer The given program reads a list...
7.6 LAB: Exception handling to detect input String vs. Integer The given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incremented. The program fails and throws an exception if the second input on a line is a String rather than an Integer. At FIXME in the code, add a try/catch statement to catch java.util.InputMismatchException, and output 0 for the age. Ex: If the input is: Lee 18 Lua...
Write a Java Program, that opens the file "students.txt" The program must read the file line...
Write a Java Program, that opens the file "students.txt" The program must read the file line by line The program parses each line that it reads For example, for this line: 1:mohamed:ali:0504123456:cs102:cs202 The program must print    >ID = 1    >First Name = Mohamed   >Last Name = Ali   >Mobie = 0504123456   >Courses = cs102, cs202 In addition, it adds the mobile phone number into an ArrayList called studentPhoneList Print the content and the size of studentPhoneList Show your results and provide...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use the file in.txt as sample input for your program. import java.io.*; import java.util.*; public class Pretty { public static final int LINE_SIZE = 50; public static void main(String[] parms) { String inputLine; int position = 1; Scanner fileIn = new Scanner(System.in); while (fileIn.hasNextLine()) { inputLine = fileIn.nextLine(); if (inputLine.equals("")) { if (position > 1) { System.out.println(); } System.out.println(); position = 1; } else {...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT