In: Computer Science
Please Code Using Java
Create a class called SoccerPlayer
Create 4 private attributes: First Name, Last Name, Games, and Goals
Have two constructors
Constructor 1 – default constructor; all values to "NONE" or zero
Constructor 2 – accepts input of first name, last name, games and goals.
Create get and set methods for each of the four attributes
Create a method the returns a double that calculates the average goals per game
This method checks for zero games played:
If there are zero played, display an error and set average to 0;
If greater than zero, do the math and set average to result of calculation
Create a test program that allows you to set the first name, last name, number of games and number of goals. Call it SoccerPlayerTest.
Create two instances of players.
The first should use the default constructor and the set methods to fill the attributes
The second should use the other constructor to set the attributes
Display the info about the players including the average goals per game.
As given in the question I have provided the below code in Java which works fine and thus I have attached an output screenshot too below.
I have created an extra method display() in the SoccerPlayer class so as to display the information of that player. Rest all the methods and attributes are created according to the question only.
Code ScreenShots:
Code:
class SoccerPlayer { private String firstName; private String lastName; private int games; private int goals; public SoccerPlayer() { firstName=null; lastName=null; games=0; goals=0; } public SoccerPlayer(String fname,String lname,int games,int goals) { firstName=fname; lastName=lname; this.games=games; this.goals=goals; } public void setFirstName(String fname) { firstName=fname; } public void setLastName(String lname) { lastName=lname; } public void setGames(int games) { this.games=games; } public void setGoals(int goals) { this.goals=goals; } public double averageGoals() { double avg; if(games==0) { avg=0; System.out.println("Error: No games played till by the Player"); return avg; } avg=(double)this.goals/this.games; return avg; } public void display() { System.out.println("Stats : \n\t Name: "+ firstName+" "+lastName+"\t Games played: "+games+"\t Goals Scored: "+goals+"\t Average Goals per Game: "+averageGoals()); } } public class SoccerPlayerTest { public static void main(String[] args) { SoccerPlayer player1 = new SoccerPlayer(); SoccerPlayer player2 = new SoccerPlayer("lio","messi",143,115); player1.setFirstName("chris"); player1.setLastName("ronaldo"); player1.setGames(170); player1.setGoals(130); player1.display(); player2.display(); } }
Output:
If there is any doubt left regarding the code do left a comment in the comments section.