SlideShare a Scribd company logo
Write a class (BasketballTeam) encapsulating the concept of a team of basketball players. This
method should have a single instance variable which is an array of basketball player objects. In
addition to that class, you will need to design and a code a Playerclass to encapsulate the concept
of a basketball player, assuming a basketball player has the following attributes: a name, a
position, number of shots taken, and number of shots made.
In your Player class you should write the following methods:
A constructor taking a String for the name, a String for the position, an int for the number of
shots taken, and an int for the number of shots made.
Accessor, mutator, toString, and equals methods.
A method returning the individual shooting percentage. Avg = Shots Made / Shots Taken. Hint:
This method should return a double!!!
In your BasketballTeam class you should write the following methods:
A constructor taking an array of Player objects as its only parameter and assigning that array to
the array data member of the class, its only instance variable.
Accessor, mutator, toString, and equals methods.
A method checking if all positions are different, returning true if they are, false if they are not.
A method returning the shooting percentage of the team. Team Shooting Percentage = Total
Shots Made / Total Shots Taken Hint: This should return a double!!! Also, this is not the average
of the the averages.
A method checking that we have a center (that is, the name of the position) on the team. If we
do not have any return false; otherwise, it returns true;
A method returning void that sorts the array of Player objects in ascending order using the
number of shots taken as the sorting key.
A method returning the array of Player objects sorted in ascending alphabetical order by name.
Hint: Use compareTo method of the String class.
A method returning the name of the player with the most shots made.
A method returning the name of the player with the highest shooting average.
In your BasketballTeamClient class, when you test all your methods, you can hard-code five
basketball Player objects. This client should call all 12 methods including the constructor for full
credit.
When writing the Player class you should write a PlayerClient class that tests all its methods
before integrating into BasketballTeam class.
Solution
public class Player {
//Attributes
private String name;
private String position;
private int shotsTaken;
private int shotsMade;
/**
* Constructor
* @param name
* @param position
* @param shotsTaken
* @param shotsMade
*/
public Player(String name, String position, int shotsTaken, int shotsMade) {
this.name = name;
this.position = position;
this.shotsTaken = shotsTaken;
this.shotsMade = shotsMade;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the position
*/
public String getPosition() {
return position;
}
/**
* @param position the position to set
*/
public void setPosition(String position) {
this.position = position;
}
/**
* @return the shotsTaken
*/
public int getShotsTaken() {
return shotsTaken;
}
/**
* @param shotsTaken the shotsTaken to set
*/
public void setShotsTaken(int shotsTaken) {
this.shotsTaken = shotsTaken;
}
/**
* @return the shotsMade
*/
public int getShotsMade() {
return shotsMade;
}
/**
* @param shotsMade the shotsMade to set
*/
public void setShotsMade(int shotsMade) {
this.shotsMade = shotsMade;
}
@Override
public String toString() {
return "Player name: " + getName() + "tPosition: " + getPosition() +
" Shots Taken: " + getShotsTaken() + "ttShots Made: " + getShotsMade();
}
@Override
public boolean equals(Object obj) {
if(obj != null) {
if(obj instanceof Player) {
Player another = (Player)obj;
if((this.getName().equalsIgnoreCase(another.getName())) &&
(this.getPosition().equalsIgnoreCase(another.getPosition())) &&
(this.getShotsMade() == another.getShotsMade()) &&
(this.getShotsTaken() == another.getShotsTaken()))
return true;
}
}
return false;
}
/**
* Returns the individual shooting percentage
* @return
*/
public double shootingPercentage() {
return ((double)getShotsMade() / getShotsTaken());
}
}
/**
* This class tests the methods of the Player class
*
* @author
*
*/
public class PlayerClient {
public static void main(String[] args) {
// Create a Player object
Player player1 = new Player("John", "Center", 10, 4);
// Create another Player object
Player player2 = new Player("Bill", "Small forward", 10, 3);
// Test toString and shootingPercentage method
System.out.println("Player 1: " + player1);
System.out.println("Shooting percentage: " + player1.shootingPercentage());
System.out.println("Player 2: " + player2);
System.out.println("Shooting percentage: " + player2.shootingPercentage());
// Test equals method
if(player1.equals(player2))
System.out.println("Both the players are same");
else
System.out.println("Both the players are different");
}
}
SAMPLE OUTPUT:
Player 1: Player name: John Position: Center
Shots Taken: 10 Shots Made: 4
Shooting percentage: 0.4
Player 2: Player name: Bill Position: Small forward
Shots Taken: 10 Shots Made: 3
Shooting percentage: 0.3
Both the players are different
public class BasketballTeam {
// Attributes
private Player[] players;
/**
* Constructors
*
* @param players
*/
public BasketballTeam(Player[] players) {
this.players = players;
}
/**
* @return the players
*/
public Player[] getPlayers() {
return players;
}
/**
* @param players
* the players to set
*/
public void setPlayers(Player[] players) {
this.players = players;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
for (Player player : players) {
sb.append(player + " ");
}
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (obj != null) {
if (obj instanceof BasketballTeam) {
BasketballTeam another = (BasketballTeam) obj;
if (this.getPlayers().length == another.getPlayers().length) {
for (int i = 0; i < this.getPlayers().length; i++) {
if (!this.players[i].equals(another.players[i]))
break;
}
return true;
}
}
}
return false;
}
/**
* Checks if all positions are different, returns true if they are, false if
* they are not.
*
* @return
*/
public boolean isDifferentPosition() {
for (int i = 0; i < this.getPlayers().length - 1; i++) {
for (int j = i + 1; j < this.getPlayers().length; j++) {
if (this.players[i].getPosition().equals(this.players[j].getPosition()))
return false;
}
}
return true;
}
/**
* Returns the team's shooting percentage
*
* @return
*/
public double shootingPercentage() {
int teamShotsMade = 0;
int teamShotsTaken = 0;
for (Player player : players) {
teamShotsMade += player.getShotsMade();
teamShotsTaken += player.getShotsTaken();
}
return ((double) teamShotsMade / teamShotsTaken);
}
/**
* Checks whether the team has a center (that is, the name of the position)
* on the team. If yes returns true; otherwise, it returns false
*
* @return
*/
public boolean isCenterPresent() {
for (Player player : players) {
if (player.getPosition().equalsIgnoreCase("Center"))
return true;
}
return false;
}
/**
* Swaps 2 players
* @param p1
* @param p2
*/
private void swap(Player p1, Player p2) {
Player temp = new Player(p1.getName(), p1.getPosition(), p1.getShotsTaken(),
p1.getShotsMade());
p1.setName(p2.getName());
p1.setPosition(p2.getPosition());
p1.setShotsMade(p2.getShotsMade());
p1.setShotsTaken(p2.getShotsTaken());
p2.setName(temp.getName());
p2.setPosition(temp.getPosition());
p2.setShotsMade(temp.getShotsMade());
p2.setShotsTaken(temp.getShotsTaken());
}
/**
* Sorts the array of Player objects in ascending order using the number of
* shots taken as the sorting key.
*/
public void sortByShotsTaken() {
for (int i = 0; i < this.players.length - 1; i++) {
for (int j = i + 1; j < this.players.length; j++) {
if (this.players[i].getShotsTaken() > this.players[j].getShotsTaken()) {
swap(this.players[i], this.players[j]);
}
}
}
}
/**
* Returns the array of Player objects sorted in ascending alphabetical order by name.
* @return
*/
public Player[] sortByName() {
// Create copy os this array
Player[] sortedArr = new Player[this.players.length];
for (int i = 0; i < sortedArr.length; i++) {
sortedArr[i] = new Player(this.players[i].getName(), this.players[i].getPosition(),
this.players[i].getShotsTaken(), this.players[i].getShotsMade());
}
for (int i = 0; i < sortedArr.length - 1; i++) {
for (int j = i + 1; j < sortedArr.length; j++) {
if (sortedArr[i].getName().compareTo(sortedArr[j].getName()) > 0) {
swap(sortedArr[i], sortedArr[j]);
}
}
}
return sortedArr;
}
/**
* Returns the name of the player with the most shots made.
*/
public String playerWithMostShotsMade() {
int index = 0;
int max = this.players[0].getShotsMade();
for (int i = 1; i < this.players.length - 1; i++) {
if(max < this.players[i].getShotsMade()) {
max = this.players[i].getShotsMade();
index = i;
}
}
return this.players[index].getName();
}
/**
* Returns the name of the player with the highest shooting average
*/
public String playerWithHighestShootingAvg() {
int index = 0;
double max = this.players[0].shootingPercentage();
for (int i = 1; i < this.players.length; i++) {
double avg = this.players[i].shootingPercentage();
if(max < avg) {
max = avg;
index = i;
}
}
return this.players[index].getName();
}
}
/**
* This class tests the methods of BasketballTeam class
*
* @author
*
*/
public class BasketballTeamClient {
public static void main(String[] args) {
// Create Player array with 5 objects
Player[] players = new Player[5];
players[0] = new Player("Bill", "Center", 10, 2);
players[1] = new Player("Joe", "Point guard", 10, 7);
players[2] = new Player("Andrew", "Shooting guard", 20, 2);
players[3] = new Player("James", "Power forward", 20, 12);
players[4] = new Player("Ben", "Small forward", 10, 4);
// Test the constructor
BasketballTeam team = new BasketballTeam(players);
// Display team
System.out.println("Team: " + team);
System.out.println();
// Check if all positions are different
System.out.println("Are all positions different? " + (team.isDifferentPosition() ? "Yes" :
"No"));
System.out.println();
// Team Shooting Percentage
System.out.println("Team Shooting Percentage: " + team.shootingPercentage());
System.out.println();
// Check if center position is present
System.out.println("Is center player available: " + (team.isCenterPresent() ? "Yes" :
"No"));
System.out.println();
// Sort array using the number of shots taken
team.sortByShotsTaken();
System.out.println("Sorted team using the number of shots taken as the sorting key: " +
team);
System.out.println();
// Sort team in ascending alphabetical order by name.
Player[] sortedArr = team.sortByName();
System.out.println("Sorted team in ascending alphabetical order by name: " );
for (Player player : sortedArr) {
System.out.println(player);
}
System.out.println();
// Player with the most shots made.
System.out.println("Player with the most shots made: " +
team.playerWithMostShotsMade());
System.out.println();
// Player with the highest shooting average.
System.out.println("Player with the highest shooting average: " +
team.playerWithHighestShootingAvg());
}
}
SAMPLE OUTPUT:
Team:
Player name: Bill Position: Center
Shots Taken: 10 Shots Made: 2
Player name: Joe Position: Point guard
Shots Taken: 10 Shots Made: 7
Player name: Andrew Position: Shooting guard
Shots Taken: 20 Shots Made: 2
Player name: James Position: Power forward
Shots Taken: 20 Shots Made: 12
Player name: Ben Position: Small forward
Shots Taken: 10 Shots Made: 4
Are all positions different? Yes
Team Shooting Percentage: 0.38571428571428573
Is center player available: Yes
Sorted team using the number of shots taken as the sorting key:
Player name: Bill Position: Center
Shots Taken: 10 Shots Made: 2
Player name: Joe Position: Point guard
Shots Taken: 10 Shots Made: 7
Player name: Ben Position: Small forward
Shots Taken: 10 Shots Made: 4
Player name: James Position: Power forward
Shots Taken: 20 Shots Made: 12
Player name: Andrew Position: Shooting guard
Shots Taken: 20 Shots Made: 2
Sorted team in ascending alphabetical order by name:
Player name: Andrew Position: Shooting guard
Shots Taken: 20 Shots Made: 2
Player name: Ben Position: Small forward
Shots Taken: 10 Shots Made: 4
Player name: Bill Position: Center
Shots Taken: 10 Shots Made: 2
Player name: James Position: Power forward
Shots Taken: 20 Shots Made: 12
Player name: Joe Position: Point guard
Shots Taken: 10 Shots Made: 7
Player with the most shots made: James
Player with the highest shooting average: Joe

More Related Content

Similar to Write a class (BasketballTeam) encapsulating the concept of a tea.pdf

Here are the instructions and then the code in a sec. Please R.pdf
Here are the instructions and then the code in a sec. Please R.pdfHere are the instructions and then the code in a sec. Please R.pdf
Here are the instructions and then the code in a sec. Please R.pdf
aggarwalshoppe14
 
Suggestion- Use Netbeans to copy your last lab (Lab 07) to a new proje.pdf
Suggestion- Use Netbeans to copy your last lab (Lab 07) to a new proje.pdfSuggestion- Use Netbeans to copy your last lab (Lab 07) to a new proje.pdf
Suggestion- Use Netbeans to copy your last lab (Lab 07) to a new proje.pdf
ssuser58be4b1
 
Use cases in the code with AOP
Use cases in the code with AOPUse cases in the code with AOP
Use cases in the code with AOP
Andrzej Krzywda
 
Save game function
Save game functionSave game function
Save game function
George Scott IV
 
Team public class Team {    private String teamId;    priva.pdf
Team public class Team {    private String teamId;    priva.pdfTeam public class Team {    private String teamId;    priva.pdf
Team public class Team {    private String teamId;    priva.pdf
DEEPAKSONI562
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
ravikapoorindia
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdf
info430661
 
codeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docx
codeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docxcodeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docx
codeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docx
monicafrancis71118
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdf
asif1401
 
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfPLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
mallik3000
 
groovy databases
groovy databasesgroovy databases
groovy databases
Paul King
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
archanaemporium
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdf
ICADCMLTPC
 
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdfIfgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
fazilfootsteps
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
Baruch Sadogursky
 

Similar to Write a class (BasketballTeam) encapsulating the concept of a tea.pdf (15)

Here are the instructions and then the code in a sec. Please R.pdf
Here are the instructions and then the code in a sec. Please R.pdfHere are the instructions and then the code in a sec. Please R.pdf
Here are the instructions and then the code in a sec. Please R.pdf
 
Suggestion- Use Netbeans to copy your last lab (Lab 07) to a new proje.pdf
Suggestion- Use Netbeans to copy your last lab (Lab 07) to a new proje.pdfSuggestion- Use Netbeans to copy your last lab (Lab 07) to a new proje.pdf
Suggestion- Use Netbeans to copy your last lab (Lab 07) to a new proje.pdf
 
Use cases in the code with AOP
Use cases in the code with AOPUse cases in the code with AOP
Use cases in the code with AOP
 
Save game function
Save game functionSave game function
Save game function
 
Team public class Team {    private String teamId;    priva.pdf
Team public class Team {    private String teamId;    priva.pdfTeam public class Team {    private String teamId;    priva.pdf
Team public class Team {    private String teamId;    priva.pdf
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdf
 
codeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docx
codeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docxcodeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docx
codeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docx
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdf
 
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfPLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
 
groovy databases
groovy databasesgroovy databases
groovy databases
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdf
 
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdfIfgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 

More from rozakashif85

Give background information concerning EMT and include what is known.pdf
Give background information concerning EMT and include what is known.pdfGive background information concerning EMT and include what is known.pdf
Give background information concerning EMT and include what is known.pdf
rozakashif85
 
Explain how the current economic recession differs from the depressio.pdf
Explain how the current economic recession differs from the depressio.pdfExplain how the current economic recession differs from the depressio.pdf
Explain how the current economic recession differs from the depressio.pdf
rozakashif85
 
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdf
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdfDoes yeast uses CopI and CopII formation for vesicle budding to grow.pdf
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdf
rozakashif85
 
DNA molecules consist of chemically linked sequences of the bases ad.pdf
DNA molecules consist of chemically linked sequences of the bases ad.pdfDNA molecules consist of chemically linked sequences of the bases ad.pdf
DNA molecules consist of chemically linked sequences of the bases ad.pdf
rozakashif85
 
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdfData StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
rozakashif85
 
Count Red Nodes. Write a program that computes the percentage of red.pdf
Count Red Nodes. Write a program that computes the percentage of red.pdfCount Red Nodes. Write a program that computes the percentage of red.pdf
Count Red Nodes. Write a program that computes the percentage of red.pdf
rozakashif85
 
apple 2008 historically what were Apples major competitive advanta.pdf
apple 2008 historically what were Apples major competitive advanta.pdfapple 2008 historically what were Apples major competitive advanta.pdf
apple 2008 historically what were Apples major competitive advanta.pdf
rozakashif85
 
A partial results from a PERT analysis for a project with 50 activit.pdf
A partial results from a PERT analysis for a project with 50 activit.pdfA partial results from a PERT analysis for a project with 50 activit.pdf
A partial results from a PERT analysis for a project with 50 activit.pdf
rozakashif85
 
briefly write about the variability of natural systems and the signi.pdf
briefly write about the variability of natural systems and the signi.pdfbriefly write about the variability of natural systems and the signi.pdf
briefly write about the variability of natural systems and the signi.pdf
rozakashif85
 
A graph is symmetric with respect to the vertical line corresponding.pdf
A graph is symmetric with respect to the vertical line corresponding.pdfA graph is symmetric with respect to the vertical line corresponding.pdf
A graph is symmetric with respect to the vertical line corresponding.pdf
rozakashif85
 
X-Linked Recessive Write three rules to keep in mind when counseling .pdf
X-Linked Recessive Write three rules to keep in mind when counseling .pdfX-Linked Recessive Write three rules to keep in mind when counseling .pdf
X-Linked Recessive Write three rules to keep in mind when counseling .pdf
rozakashif85
 
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdfWrite a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
rozakashif85
 
Which of the following would you expect to happen in a plant that doe.pdf
Which of the following would you expect to happen in a plant that doe.pdfWhich of the following would you expect to happen in a plant that doe.pdf
Which of the following would you expect to happen in a plant that doe.pdf
rozakashif85
 
What is the value of including personal information about yourself a.pdf
What is the value of including personal information about yourself a.pdfWhat is the value of including personal information about yourself a.pdf
What is the value of including personal information about yourself a.pdf
rozakashif85
 
What is a voluntary response sampleSolutionVoluntary response.pdf
What is a voluntary response sampleSolutionVoluntary response.pdfWhat is a voluntary response sampleSolutionVoluntary response.pdf
What is a voluntary response sampleSolutionVoluntary response.pdf
rozakashif85
 
What adaptive benefit do these abilities give wolbachia In oth.pdf
What adaptive benefit do these abilities give wolbachia In oth.pdfWhat adaptive benefit do these abilities give wolbachia In oth.pdf
What adaptive benefit do these abilities give wolbachia In oth.pdf
rozakashif85
 
Think about autumn (Fall season) in places like New England (Pennsyl.pdf
Think about autumn (Fall season) in places like New England (Pennsyl.pdfThink about autumn (Fall season) in places like New England (Pennsyl.pdf
Think about autumn (Fall season) in places like New England (Pennsyl.pdf
rozakashif85
 
The orange is which type of fruit Simple - Legume Simple - Drupe .pdf
The orange is which type of fruit  Simple - Legume  Simple - Drupe  .pdfThe orange is which type of fruit  Simple - Legume  Simple - Drupe  .pdf
The orange is which type of fruit Simple - Legume Simple - Drupe .pdf
rozakashif85
 
The _________ is the protective chamber that houses the ovule and Lat.pdf
The _________ is the protective chamber that houses the ovule and Lat.pdfThe _________ is the protective chamber that houses the ovule and Lat.pdf
The _________ is the protective chamber that houses the ovule and Lat.pdf
rozakashif85
 
Suppose X follows a normal distribution with mean=1 and variance=4. .pdf
Suppose X follows a normal distribution with mean=1 and variance=4. .pdfSuppose X follows a normal distribution with mean=1 and variance=4. .pdf
Suppose X follows a normal distribution with mean=1 and variance=4. .pdf
rozakashif85
 

More from rozakashif85 (20)

Give background information concerning EMT and include what is known.pdf
Give background information concerning EMT and include what is known.pdfGive background information concerning EMT and include what is known.pdf
Give background information concerning EMT and include what is known.pdf
 
Explain how the current economic recession differs from the depressio.pdf
Explain how the current economic recession differs from the depressio.pdfExplain how the current economic recession differs from the depressio.pdf
Explain how the current economic recession differs from the depressio.pdf
 
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdf
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdfDoes yeast uses CopI and CopII formation for vesicle budding to grow.pdf
Does yeast uses CopI and CopII formation for vesicle budding to grow.pdf
 
DNA molecules consist of chemically linked sequences of the bases ad.pdf
DNA molecules consist of chemically linked sequences of the bases ad.pdfDNA molecules consist of chemically linked sequences of the bases ad.pdf
DNA molecules consist of chemically linked sequences of the bases ad.pdf
 
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdfData StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
Data StructuresPLEASE USING THIS C++ PROGRAM BELOW, I NEED HEL.pdf
 
Count Red Nodes. Write a program that computes the percentage of red.pdf
Count Red Nodes. Write a program that computes the percentage of red.pdfCount Red Nodes. Write a program that computes the percentage of red.pdf
Count Red Nodes. Write a program that computes the percentage of red.pdf
 
apple 2008 historically what were Apples major competitive advanta.pdf
apple 2008 historically what were Apples major competitive advanta.pdfapple 2008 historically what were Apples major competitive advanta.pdf
apple 2008 historically what were Apples major competitive advanta.pdf
 
A partial results from a PERT analysis for a project with 50 activit.pdf
A partial results from a PERT analysis for a project with 50 activit.pdfA partial results from a PERT analysis for a project with 50 activit.pdf
A partial results from a PERT analysis for a project with 50 activit.pdf
 
briefly write about the variability of natural systems and the signi.pdf
briefly write about the variability of natural systems and the signi.pdfbriefly write about the variability of natural systems and the signi.pdf
briefly write about the variability of natural systems and the signi.pdf
 
A graph is symmetric with respect to the vertical line corresponding.pdf
A graph is symmetric with respect to the vertical line corresponding.pdfA graph is symmetric with respect to the vertical line corresponding.pdf
A graph is symmetric with respect to the vertical line corresponding.pdf
 
X-Linked Recessive Write three rules to keep in mind when counseling .pdf
X-Linked Recessive Write three rules to keep in mind when counseling .pdfX-Linked Recessive Write three rules to keep in mind when counseling .pdf
X-Linked Recessive Write three rules to keep in mind when counseling .pdf
 
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdfWrite a Java Class to Implement a Generic Linked ListYour list mus.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
 
Which of the following would you expect to happen in a plant that doe.pdf
Which of the following would you expect to happen in a plant that doe.pdfWhich of the following would you expect to happen in a plant that doe.pdf
Which of the following would you expect to happen in a plant that doe.pdf
 
What is the value of including personal information about yourself a.pdf
What is the value of including personal information about yourself a.pdfWhat is the value of including personal information about yourself a.pdf
What is the value of including personal information about yourself a.pdf
 
What is a voluntary response sampleSolutionVoluntary response.pdf
What is a voluntary response sampleSolutionVoluntary response.pdfWhat is a voluntary response sampleSolutionVoluntary response.pdf
What is a voluntary response sampleSolutionVoluntary response.pdf
 
What adaptive benefit do these abilities give wolbachia In oth.pdf
What adaptive benefit do these abilities give wolbachia In oth.pdfWhat adaptive benefit do these abilities give wolbachia In oth.pdf
What adaptive benefit do these abilities give wolbachia In oth.pdf
 
Think about autumn (Fall season) in places like New England (Pennsyl.pdf
Think about autumn (Fall season) in places like New England (Pennsyl.pdfThink about autumn (Fall season) in places like New England (Pennsyl.pdf
Think about autumn (Fall season) in places like New England (Pennsyl.pdf
 
The orange is which type of fruit Simple - Legume Simple - Drupe .pdf
The orange is which type of fruit  Simple - Legume  Simple - Drupe  .pdfThe orange is which type of fruit  Simple - Legume  Simple - Drupe  .pdf
The orange is which type of fruit Simple - Legume Simple - Drupe .pdf
 
The _________ is the protective chamber that houses the ovule and Lat.pdf
The _________ is the protective chamber that houses the ovule and Lat.pdfThe _________ is the protective chamber that houses the ovule and Lat.pdf
The _________ is the protective chamber that houses the ovule and Lat.pdf
 
Suppose X follows a normal distribution with mean=1 and variance=4. .pdf
Suppose X follows a normal distribution with mean=1 and variance=4. .pdfSuppose X follows a normal distribution with mean=1 and variance=4. .pdf
Suppose X follows a normal distribution with mean=1 and variance=4. .pdf
 

Recently uploaded

Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 

Recently uploaded (20)

Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 

Write a class (BasketballTeam) encapsulating the concept of a tea.pdf

  • 1. Write a class (BasketballTeam) encapsulating the concept of a team of basketball players. This method should have a single instance variable which is an array of basketball player objects. In addition to that class, you will need to design and a code a Playerclass to encapsulate the concept of a basketball player, assuming a basketball player has the following attributes: a name, a position, number of shots taken, and number of shots made. In your Player class you should write the following methods: A constructor taking a String for the name, a String for the position, an int for the number of shots taken, and an int for the number of shots made. Accessor, mutator, toString, and equals methods. A method returning the individual shooting percentage. Avg = Shots Made / Shots Taken. Hint: This method should return a double!!! In your BasketballTeam class you should write the following methods: A constructor taking an array of Player objects as its only parameter and assigning that array to the array data member of the class, its only instance variable. Accessor, mutator, toString, and equals methods. A method checking if all positions are different, returning true if they are, false if they are not. A method returning the shooting percentage of the team. Team Shooting Percentage = Total Shots Made / Total Shots Taken Hint: This should return a double!!! Also, this is not the average of the the averages. A method checking that we have a center (that is, the name of the position) on the team. If we do not have any return false; otherwise, it returns true; A method returning void that sorts the array of Player objects in ascending order using the number of shots taken as the sorting key. A method returning the array of Player objects sorted in ascending alphabetical order by name. Hint: Use compareTo method of the String class. A method returning the name of the player with the most shots made. A method returning the name of the player with the highest shooting average. In your BasketballTeamClient class, when you test all your methods, you can hard-code five basketball Player objects. This client should call all 12 methods including the constructor for full credit. When writing the Player class you should write a PlayerClient class that tests all its methods before integrating into BasketballTeam class. Solution
  • 2. public class Player { //Attributes private String name; private String position; private int shotsTaken; private int shotsMade; /** * Constructor * @param name * @param position * @param shotsTaken * @param shotsMade */ public Player(String name, String position, int shotsTaken, int shotsMade) { this.name = name; this.position = position; this.shotsTaken = shotsTaken; this.shotsMade = shotsMade; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the position */
  • 3. public String getPosition() { return position; } /** * @param position the position to set */ public void setPosition(String position) { this.position = position; } /** * @return the shotsTaken */ public int getShotsTaken() { return shotsTaken; } /** * @param shotsTaken the shotsTaken to set */ public void setShotsTaken(int shotsTaken) { this.shotsTaken = shotsTaken; } /** * @return the shotsMade */ public int getShotsMade() { return shotsMade; } /** * @param shotsMade the shotsMade to set */ public void setShotsMade(int shotsMade) { this.shotsMade = shotsMade; } @Override public String toString() { return "Player name: " + getName() + "tPosition: " + getPosition() +
  • 4. " Shots Taken: " + getShotsTaken() + "ttShots Made: " + getShotsMade(); } @Override public boolean equals(Object obj) { if(obj != null) { if(obj instanceof Player) { Player another = (Player)obj; if((this.getName().equalsIgnoreCase(another.getName())) && (this.getPosition().equalsIgnoreCase(another.getPosition())) && (this.getShotsMade() == another.getShotsMade()) && (this.getShotsTaken() == another.getShotsTaken())) return true; } } return false; } /** * Returns the individual shooting percentage * @return */ public double shootingPercentage() { return ((double)getShotsMade() / getShotsTaken()); } } /** * This class tests the methods of the Player class * * @author * */ public class PlayerClient { public static void main(String[] args) { // Create a Player object Player player1 = new Player("John", "Center", 10, 4);
  • 5. // Create another Player object Player player2 = new Player("Bill", "Small forward", 10, 3); // Test toString and shootingPercentage method System.out.println("Player 1: " + player1); System.out.println("Shooting percentage: " + player1.shootingPercentage()); System.out.println("Player 2: " + player2); System.out.println("Shooting percentage: " + player2.shootingPercentage()); // Test equals method if(player1.equals(player2)) System.out.println("Both the players are same"); else System.out.println("Both the players are different"); } } SAMPLE OUTPUT: Player 1: Player name: John Position: Center Shots Taken: 10 Shots Made: 4 Shooting percentage: 0.4 Player 2: Player name: Bill Position: Small forward Shots Taken: 10 Shots Made: 3 Shooting percentage: 0.3 Both the players are different public class BasketballTeam { // Attributes private Player[] players; /** * Constructors * * @param players */ public BasketballTeam(Player[] players) { this.players = players; } /** * @return the players
  • 6. */ public Player[] getPlayers() { return players; } /** * @param players * the players to set */ public void setPlayers(Player[] players) { this.players = players; } @Override public String toString() { StringBuffer sb = new StringBuffer(); for (Player player : players) { sb.append(player + " "); } return sb.toString(); } @Override public boolean equals(Object obj) { if (obj != null) { if (obj instanceof BasketballTeam) { BasketballTeam another = (BasketballTeam) obj; if (this.getPlayers().length == another.getPlayers().length) { for (int i = 0; i < this.getPlayers().length; i++) { if (!this.players[i].equals(another.players[i])) break; } return true; } } } return false; } /**
  • 7. * Checks if all positions are different, returns true if they are, false if * they are not. * * @return */ public boolean isDifferentPosition() { for (int i = 0; i < this.getPlayers().length - 1; i++) { for (int j = i + 1; j < this.getPlayers().length; j++) { if (this.players[i].getPosition().equals(this.players[j].getPosition())) return false; } } return true; } /** * Returns the team's shooting percentage * * @return */ public double shootingPercentage() { int teamShotsMade = 0; int teamShotsTaken = 0; for (Player player : players) { teamShotsMade += player.getShotsMade(); teamShotsTaken += player.getShotsTaken(); } return ((double) teamShotsMade / teamShotsTaken); } /** * Checks whether the team has a center (that is, the name of the position) * on the team. If yes returns true; otherwise, it returns false * * @return */ public boolean isCenterPresent() { for (Player player : players) {
  • 8. if (player.getPosition().equalsIgnoreCase("Center")) return true; } return false; } /** * Swaps 2 players * @param p1 * @param p2 */ private void swap(Player p1, Player p2) { Player temp = new Player(p1.getName(), p1.getPosition(), p1.getShotsTaken(), p1.getShotsMade()); p1.setName(p2.getName()); p1.setPosition(p2.getPosition()); p1.setShotsMade(p2.getShotsMade()); p1.setShotsTaken(p2.getShotsTaken()); p2.setName(temp.getName()); p2.setPosition(temp.getPosition()); p2.setShotsMade(temp.getShotsMade()); p2.setShotsTaken(temp.getShotsTaken()); } /** * Sorts the array of Player objects in ascending order using the number of * shots taken as the sorting key. */ public void sortByShotsTaken() { for (int i = 0; i < this.players.length - 1; i++) { for (int j = i + 1; j < this.players.length; j++) { if (this.players[i].getShotsTaken() > this.players[j].getShotsTaken()) { swap(this.players[i], this.players[j]); } }
  • 9. } } /** * Returns the array of Player objects sorted in ascending alphabetical order by name. * @return */ public Player[] sortByName() { // Create copy os this array Player[] sortedArr = new Player[this.players.length]; for (int i = 0; i < sortedArr.length; i++) { sortedArr[i] = new Player(this.players[i].getName(), this.players[i].getPosition(), this.players[i].getShotsTaken(), this.players[i].getShotsMade()); } for (int i = 0; i < sortedArr.length - 1; i++) { for (int j = i + 1; j < sortedArr.length; j++) { if (sortedArr[i].getName().compareTo(sortedArr[j].getName()) > 0) { swap(sortedArr[i], sortedArr[j]); } } } return sortedArr; } /** * Returns the name of the player with the most shots made. */ public String playerWithMostShotsMade() { int index = 0; int max = this.players[0].getShotsMade(); for (int i = 1; i < this.players.length - 1; i++) { if(max < this.players[i].getShotsMade()) { max = this.players[i].getShotsMade(); index = i;
  • 10. } } return this.players[index].getName(); } /** * Returns the name of the player with the highest shooting average */ public String playerWithHighestShootingAvg() { int index = 0; double max = this.players[0].shootingPercentage(); for (int i = 1; i < this.players.length; i++) { double avg = this.players[i].shootingPercentage(); if(max < avg) { max = avg; index = i; } } return this.players[index].getName(); } } /** * This class tests the methods of BasketballTeam class * * @author * */ public class BasketballTeamClient { public static void main(String[] args) { // Create Player array with 5 objects Player[] players = new Player[5]; players[0] = new Player("Bill", "Center", 10, 2); players[1] = new Player("Joe", "Point guard", 10, 7); players[2] = new Player("Andrew", "Shooting guard", 20, 2); players[3] = new Player("James", "Power forward", 20, 12); players[4] = new Player("Ben", "Small forward", 10, 4);
  • 11. // Test the constructor BasketballTeam team = new BasketballTeam(players); // Display team System.out.println("Team: " + team); System.out.println(); // Check if all positions are different System.out.println("Are all positions different? " + (team.isDifferentPosition() ? "Yes" : "No")); System.out.println(); // Team Shooting Percentage System.out.println("Team Shooting Percentage: " + team.shootingPercentage()); System.out.println(); // Check if center position is present System.out.println("Is center player available: " + (team.isCenterPresent() ? "Yes" : "No")); System.out.println(); // Sort array using the number of shots taken team.sortByShotsTaken(); System.out.println("Sorted team using the number of shots taken as the sorting key: " + team); System.out.println(); // Sort team in ascending alphabetical order by name. Player[] sortedArr = team.sortByName(); System.out.println("Sorted team in ascending alphabetical order by name: " ); for (Player player : sortedArr) { System.out.println(player); } System.out.println(); // Player with the most shots made. System.out.println("Player with the most shots made: " + team.playerWithMostShotsMade()); System.out.println(); // Player with the highest shooting average. System.out.println("Player with the highest shooting average: " + team.playerWithHighestShootingAvg()); }
  • 12. } SAMPLE OUTPUT: Team: Player name: Bill Position: Center Shots Taken: 10 Shots Made: 2 Player name: Joe Position: Point guard Shots Taken: 10 Shots Made: 7 Player name: Andrew Position: Shooting guard Shots Taken: 20 Shots Made: 2 Player name: James Position: Power forward Shots Taken: 20 Shots Made: 12 Player name: Ben Position: Small forward Shots Taken: 10 Shots Made: 4 Are all positions different? Yes Team Shooting Percentage: 0.38571428571428573 Is center player available: Yes Sorted team using the number of shots taken as the sorting key: Player name: Bill Position: Center Shots Taken: 10 Shots Made: 2 Player name: Joe Position: Point guard Shots Taken: 10 Shots Made: 7 Player name: Ben Position: Small forward Shots Taken: 10 Shots Made: 4 Player name: James Position: Power forward Shots Taken: 20 Shots Made: 12 Player name: Andrew Position: Shooting guard Shots Taken: 20 Shots Made: 2 Sorted team in ascending alphabetical order by name: Player name: Andrew Position: Shooting guard Shots Taken: 20 Shots Made: 2 Player name: Ben Position: Small forward Shots Taken: 10 Shots Made: 4 Player name: Bill Position: Center Shots Taken: 10 Shots Made: 2
  • 13. Player name: James Position: Power forward Shots Taken: 20 Shots Made: 12 Player name: Joe Position: Point guard Shots Taken: 10 Shots Made: 7 Player with the most shots made: James Player with the highest shooting average: Joe