This is a generic class with bound type Player.
public class Team<T extends Player> implements Comparable<Team<T>> {
private String name;
private int played=0;
private int won=0;
private int lost=0;
private int tide=0;
private ArrayList<T> members = new ArrayList<>();
public Team(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getWon() {
return won;
}
public boolean addPlayer(T player){
if(members.contains(player)){
System.out.println(player.getName() + " is already on this team" );
return false;
}else{
members.add(player);
System.out.println(player.getName()+" picked for team "+this.name);
return true;
}
}
public int numPlayer(){
return this.members.size();
}
}
This is a generic class with bound Type as Team.
public class League<T extends Team>{
public String name;
private ArrayList<T> league = new ArrayList<>();
public League(String name) {
this.name = name;
}
public boolean addTeam(T team){
if(league.contains(team)){
System.out.println("It is already exist");
return false;
}else{
league.add(team);
return true;
}
}
public void showLeagueTable(){
Collections.sort(league);
for(T t:league){
System.out.println(t.getName()+" : "+t.ranking());
}
}
}
I don't know how to create an object for the League class, literally not able to figure out how to mention type. I've tried several ways, but none of them worked for me. Could you guys help me with this code?
Related
I just started learning Guice, but I've already encountered a problem. I have an interface PlayerFactory with one implementation BlackjackPlayer
PlayerFactory.java
public interface PlayerFactory {
Player createPlayer(String name);
Player createPlayer(String name, boolean isDealer);
}
BlackjackPlayer.java
public class BlackjackPlayer implements PlayerFactory {
private PointsCalculator pointsCalculator;
public BlackjackPlayer(){
pointsCalculator = new BlackjackPointsCalculator();
}
#Override
public Player createPlayer(String name) {
return new Player(pointsCalculator, name);
}
#Override
public Player createPlayer(String name, boolean isDealer) {
return new Player(pointsCalculator, name, isDealer);
}
}
Player.class
public class Player{
private PointsCalculator pointsCalculator;
private List<Card> cardsInHand;
private Integer points;
private String name;
private boolean isDealer;
private boolean endedTurn;
#AssistedInject
public Player(PointsCalculator blackjackPointsCalculator, String name){
pointsCalculator = blackjackPointsCalculator;
cardsInHand = new ArrayList<>();
points = 0;
this.name = name;
isDealer = false;
endedTurn = false;
}
#AssistedInject
public Player(PointsCalculator blackjackPointsCalculator, String name, boolean isDealer){
pointsCalculator = blackjackPointsCalculator;
cardsInHand = new ArrayList<>();
points = 0;
this.name = name;
this.isDealer = isDealer;
endedTurn = false;
}
public void addCardToHand(Card card) {
cardsInHand.add(card);
updatePoints();
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Player)) return false;
Player player = (Player) o;
return getPoints() == player.getPoints() &&
isDealer() == player.isDealer() &&
isEndedTurn() == player.isEndedTurn() &&
Objects.equals(pointsCalculator, player.pointsCalculator) &&
Objects.equals(getCardsInHand(), player.getCardsInHand()) &&
Objects.equals(getName(), player.getName());
}
#Override
public int hashCode() {
return Objects.hash(pointsCalculator, getCardsInHand(), getPoints(), getName(), isDealer(), isEndedTurn());
}
public void updatePoints() {
points = pointsCalculator.calculatePoints(cardsInHand);
}
public List<Card> getCardsInHand(){
return cardsInHand;
}
public Integer getPoints(){
return points;
}
public String getName(){
return name;
}
public boolean isDealer() {
return isDealer;
}
public boolean isEndedTurn() {
return endedTurn;
}
public void setName(String name){
this.name = name;
}
public void setDealer(boolean isDealer){
this.isDealer = isDealer;
}
public void setEndedTurn(boolean endedTurn){
this.endedTurn = endedTurn;
}
}
I want to use Guice assisted inject to create Player. Previously I did it as follows:
install(new FactoryModuleBuilder().build(PlayerFactory.class));
which I know is wrong way, because I receive error message:
1) com.github.blackjack.model.Player has #AssistedInject constructors, but none of them match the parameters in method com.github.blackjack.factory.PlayerFactory.createPlayer(). Unable to create AssistedInject factory.
while locating com.github.blackjack.model.Player
at com.github.blackjack.factory.PlayerFactory.createPlayer(PlayerFactory.java:1)
2) com.github.blackjack.model.Player has #AssistedInject constructors, but none of them match the parameters in method com.github.blackjack.factory.PlayerFactory.createPlayer(). Unable to create AssistedInject factory.
while locating com.github.blackjack.model.Player
at com.github.blackjack.factory.PlayerFactory.createPlayer(PlayerFactory.java:1)
I tried to add constructors Player(String name), Player(String name, boolean isDealer) but it didn't help. Does someone know what should I do to fix the problem?
Thanks in advance!
You need to use the #Assisted annotation on the injectee parameters:
PlayerFactory.java
public interface PlayerFactory {
Player createPlayer(String name);
Player createPlayer(String name, boolean isDealer);
}
BlackjackPlayer.java (Change it from a factory to the actual player)
public class BlackjackPlayer implements Player {
private final PointCalculator pointsCalculator;
private final String name;
private final boolean isDealer;
#AssistedInject BlackjackPlayer(PointCalculator pointsCalculator, #Assisted String name) {
this.pointsCalculator = pointsCalculator;
this.name = name;
this.isDealer = false;
}
#AssistedInject BlackjackPlayer(PointCalculator pointsCalculator, #Assisted String name, #Assisted boolean isDealer) {
this.pointsCalculator = pointsCalculator;
this.name = name;
this.isDealer = isDealer;
}
}
And use the module as the following:
install(new FactoryModuleBuilder()
.implement(Player.class, BlackjackPlayer.class)
.build(PlayerFactory.class)
);
I have created an Object called "Item", and I want to serialize an ArrayList with Items inside it. My program works perfectly with an ArrayList<String>, but it doesn't work with an ArrayList<Item>. I believe it has to do with my Object. Here it is:
public class Item implements Serializable{
private static String name;
private static BufferedImage picture;
private static boolean craftable;
private static Item[][] craftTable;
private static boolean smeltable;
private static Item smelt_ancestor;
private static Item smelt_descendant;
public Item(String name, boolean craftable, boolean smeltable){
this.name = name;
this.craftable = craftable;
if(craftable){
craftTable = new Item[3][3];
}else{
craftTable = null;
}
this.picture = null;
this.smeltable = smeltable;
this.smelt_ancestor = null;
this.smelt_descendant = null;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public BufferedImage getPicture(){
return picture;
}
public boolean setPicture(){
boolean verify = false;
String pictureName = name.replaceAll("\\s+","");
String newNamePng = pictureName + ".png";
String newNameJpg = pictureName + ".jpg";
File imagePng = new File(newNamePng);
File imageJpg = new File(newNameJpg);
if(imagePng.exists()){
return true;
}else if(imageJpg.exists()){
return true;
}else{
return false;
}
}
public boolean getCraftable(){
return craftable;
}
public void setCraftable(boolean value){
this.craftable = value;
}
public boolean setCraftTable(Item[][] table){
if(this.craftable==true){
craftTable = table;
return true;
}else{
return false;
}
}
public Item[][] getCraftTable(){
return craftTable;
}
public boolean getSmeltable(){
return smeltable;
}
public void setSmeltable(boolean value){
smeltable = value;
}
public Item getAncestor(){
return smelt_ancestor;
}
public void setAncestor(Item ancestor){
smelt_ancestor = ancestor;
}
public Item getDescendant(){
return smelt_descendant;
}
public void setDescendant(Item des){
smelt_descendant = des;
}
public String toString(){
return name;
}
Ignore the imports, I use them in other methods I omitted because they work perfectly. Is there anything wrong with the Object that could stop it from being serialized correctly?
Static variables are not serialized. It looks like you probably want those to be non-static instance variables.
Serialization by definition is applied on objects and not classes.
It copies the state of an object to be transferred over a network or a stream or to be stored.
Your usage of static variables make them class variables, and hence they do not contribute to the state of an object. First thing to do would be make them non-static.
This leaves us with your class, which is already Serializable and so is ArrayList. You can just serialize them and de-serialize them using ObjectInputStream and ObjectOutputStream and by making sure you have the same class in the classpath at the Deserialization end.
The following class keeps giving me a null pointer when I try to call the addPlayer method and I have no idea what the heck I'm doing wrong. : Keep in mind this is really simple stuff...supposedly... I'm learning Java.
import java.util.*;
public class Team {
private String teamName;
private ArrayList<Player> players;
private int numberOfPlayers;
public Team(String teamName) {
this.teamName = teamName;
}
public String getName() {
return this.teamName;
}
public void addPlayer(Player player) {
this.players.add(player);
}
public void printPlayers() {
for (Player player : this.players) {
System.out.println(player);
}
}
}
Here is the Player class :
public class Player {
private String name;
private int goals;
public Player(String name) {
this.name = name;
}
public Player(String name, int goals) {
this.name = name;
this.goals = goals;
}
#Override
public String toString() {
return this.getName() + ", goals " + this.goals();
}
public String getName () {
return this.name;
}
public int goals() {
return this.goals;
}
}
This is your problem:
private ArrayList<Player> players;
is not initialized, you never create a new one when you instantiate your class.
Add the following to your constructor:
public Team(String teamName) {
this.teamName = teamName;
this.players = new ArrayList<Player>();
}
You haven't initialized the variable, thus its value is null.
private ArrayList<Player> players = new ArrayList<Player>();
That should fix it.
You have declared an ArrayList but where is the initialization??
Fix it by initializing the ArrayList as :
private ArrayList<Player> players = new ArrayList<Player>();
I have two classes: profesor and subject
public class Profesor {
private int numbClassroom;
public Profesor(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public int getNumbClassroom() {
return numbClassroom;
}
public void setNumbClassroom(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public String ToString(){
return "Number of classroom: "+numbClassroom;
} }
The second class is:
public class Subject{
String name;
Profesor lecturer = new Profesor();
Date yearOfStudy;
public void Dodeli(Profesor p){
??????
}}
I do not know how to add professor like a lecturer to a current subject
Like this? I don't see any problem.
public void Dodeli(Profesor p){
lecturer = p;
}
Profesor lecturer = new Profesor();
No need to instantiate lecturer. Just declare it. Then have getter/setter methods for it
Then you can assign Professor to Subject
Subject subj = new Subject("OOP"); //assuming you have corresponding constructor
subj.setLecturer(new Professor()); //or if you have existing prof object
Maybe require something like this : try to encapsulate your code
public class Professor {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Subject{
private String name;
private Professor professor;
private int numbClassroom;
private Date yearOfStudy;
public int getNumbClassroom() {
return numbClassroom;
}
public void setNumbClassroom(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Professor getProfesor() {
return professor;
}
public void setProfesor(Professor profesor) {
this.professor = profesor;
}
public void Dodeli(){
System.out.println("Pofessor "+getProfesor().getName()+" is teaching "+getName()+" in Room NO :"+getNumbClassroom());
}
}
public class TestImpl {
public static void main(String arr[])
{
Subject subject = new Subject();
Professor professor = new Professor();
subject.setName("Biology");
professor.setName("MR.X");
subject.setNumbClassroom(1111);
subject.setProfesor(professor);
subject.Dodeli();
}
}
I'm making a little game with a hero having inventory filled with object.
public enum Objects_type
{
WEAPON,
ARMOR
}
public abstract class Objects_class
{
protected String name;
protected Objects_type type;
public Objects_class(String name, Objects_type type)
{
this.name = name;
this.type = type;
}
}
public abstract class Armor extends Objects_class{
int life = 0;
int res_fire = 0;
public Armor(String name, int largeur, int hauteur) {
super(name, Objects_type.ARMOR);
}
}
public abstract class Weapon extends Objects_class
{
protected int dmg_fire = 0;
public Weapon(String name) {
super(name, Objects_type.WEAPON);
}
}
public class StickOfJoy extends Weapon{
public StickOfJoy() {
super("Stick of Joy");
dmg_fire = 2;
}
}
public class ArmorOfPity extends Armor{
public ArmorOfPity()
{
super("Armor of Pity");
life = 30;
}
}
Then I have functions like :
Hero.getObject (Objects_class obj)
{
if (obj.getType == Objects_type.WEAPON)
....
}
I'd like to be able to consider the Objects_class obj as a Weapon but of course it's not possible (casting a mother to its child) so it makes me think my inheritance structure is bad.
What should I've done ?
David Conrad has some good points I recommend you read through that I won't repeat here but here is how I would do it.
Suppose you have a character that is roaming around in your game world picking up items, there can be many different items, some so different from each other in behavior they warrant the creation of a new subclass (like picking up boots vs picking up wings).
Once you pick up an item, you have the choice of letting the hero try and see what kind of item was picked up (instanceof, enums, whatever) or you can let the item figure out where it is supposed to go.
Here is a simplified example where the player has only two inventory slots, a weapon and an armor. Notice how easy it is to simply add a new item (like a health potion, or a superdupernewspecialweapon) to the mix without having to change anything in the player or do casting.
public abstract class Item {
private int ID;
private static int IDCounter;
private String name;
public Item(String name) {
this.name = name;
this.ID = IDCounter;
IDCounter++;
}
public int getID() {
return ID;
}
public String getName() {
return name;
}
public abstract void attachToPlayer(Player player);
}
public class Armor extends Item {
private int life;
private int res_fire;
public Armor(String name) {
super(name);
}
#Override
public void attachToPlayer(Player player) {
// Only equip if upgrade
if (player.getArmor().res_fire > this.res_fire)
player.setArmor(this);
}
}
public class Weapon extends Item {
private int dmg_fire;
public Weapon(String name) {
super(name);
}
// ...stuff
#Override
public void attachToPlayer(Player player) {
// Only equip this if upgrade? You decide the logic
if(player.getWeapon().dmg_fire>this.dmg_fire)
player.setWeapon(this);
}
}
public class SuperSpecialWeapon extends Weapon {
private float bonusHealthModifier = 1.0f;
public SuperSpecialWeapon(String name) {
super(name);
}
#Override
public void attachToPlayer(Player player) {
// This bonus adds +100%HP bonus to the player!
int hp = (int) ((1 + bonusHealthModifier) * player.getHealth());
player.setHealth(hp);
player.setWeapon(this);
}
}
public class Potion extends Item {
private int health = 100;
public Potion() {
super("HealthPotion");
}
#Override
public void attachToPlayer(Player player) {
// If the player has room for one more potion, pick this up
Potion[] potions = player.getHealthPotions();
for (int i = 0; i < potions.length; i++) {
if(potions[i]==null){
potions[i] = this;
break;
}
}
}
// ..other stuff
}
And finally the player
public class Player {
private Armor armor;
private Weapon weapon;
private String name;
private Potion[] healthPotions = new Potion[10];
private int health;
public Player(String name) {
this.name = name;
}
public Armor getArmor() {
return armor;
}
public Weapon getWeapon() {
return weapon;
}
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
public void setArmor(Armor armor) {
this.armor = armor;
}
public void setHealth(int health) {
this.health = health;
}
public int getHealth() {
return health;
}
public Potion[] getHealthPotions() {
return healthPotions;
}
}
There is no need of Objects_type, since objects in Java know what type they are, and their type can be tested with the instanceof operator. You say that you cannot cast "a mother to its child", but it is possible to downcast an object to a child type. In general, it could throw a ClassCastException, but if you have tested it first with instanceof, that won't happen.
public class Objects_class {
protected String name;
public Objects_class(String name) {
this.name = name;
}
}
public class Armor extends Objects_class {
int life = 0;
int res_fire = 0;
public Armor(String name, int largeur, int hauteur) {
super(name);
}
}
public class Weapon extends Objects_class {
protected int dmg_fire = 0;
public Weapon(String name) {
super(name);
}
}
public class Hero {
public void getObject(Objects_class obj) {
if (obj instanceof Weapon) {
Weapon weapon = (Weapon) obj;
wield(weapon);
}
if (obj instanceof Armor) {
Armor armor = (Armor) obj;
wear(armor);
}
}
}
I have removed the abstract modifier from the classes since there is no need of it, but perhaps you wanted it to ensure that those base classes are never instantiated. Also, I would change the name of Objects_class to something like Item since the words Object and class have particular meanings that could cause confusion. I would also rename Hero's getObject method to something like pickUpItem since it isn't a getter, in the Java sense.