Are enums changeable at all? - java

I've been working on a game, and in the game I'm a summoner that has tamed monsters (much like pokemon).
What I want to do , is have a backpack of 5 tamed monsters, of which I can spawn 1 at a time.
Someone recommended me to use enums (I can't contact that person anymore :(), so I've been looking at a few enum tutorials and examples, and I can't figure out how this would help me.
Let us say that the enum would look like this :
public enum TamedMonsterStats {
ELF(0,"res/siren_monster_girl_sprite_by_tsarcube-d52y2zu.png",0,100);
DRAGON(0,"res/dragon.png",0,100);
private int haveit;
private String photoname;
private int typeOfDamage;/*
* 0: dark
* 1: light
* 2:
*/
private int HP;
TamedMonsterStats(int haveit,String photoname,int typeOfDamage,int HP){
this.haveit = haveit;
this.photoname = photoname;
this.typeOfDamage = typeOfDamage;
this.HP = HP;
}
public int getHaveIt(){
return haveit;
}
public String getPhotoName(){
return photoname;
}
public int getTypeOfDamage(){
return typeOfDamage;
}
public int getHP(){
return HP;
}
public void setHp(int hp) {
HP = hp;
}
}
This would kind of work, but as daveychu pointed out, this makes it impossible for me to have 2 instances of the same creature, so my idea was to have an enum backpack with monster1,monster2,monster3,monster4,monster5 , and then filling them with the values dynamically, but I feel like doing this means I shouldn't be requiring enums at all, is this true?

You can add a setter method on your enum:
public void setHp(int hp) {
HP = hp;
}
However, I'm a bit wary of your use of enum. In this situation, only one "DRAGON" instance could exist at any time so I wonder what you would do if the user wants to have more of them or if the enemy has one at the same time.
Your typeOfDamage on the other hand is an excellent candidate for an enum:
public enum DamageType {
DARK,
LIGHT,
NORMAL
}
You can then use this enum:
ELF(0, "res/siren_monster_girl_sprite_by_tsarcube-d52y2zu.png", DamageType.DARK, 100),
DRAGON(0, "res/dragon.png", DamageType.LIGHT, 100);
private DamageType typeOfDamage;
TamedMonsterStats(int haveit, String photoname, DamageType typeOfDamage, int HP) {
this.typeOfDamage = typeOfDamage;
}
public DamageType getTypeOfDamage() {
return typeOfDamage;
}
It makes it a lot more readable than having to pass some random integers.

Related

Problem with not allowed to use Boolean as a data type

I'm trying to create a Sub-class for a program that creates a list with different objects.
One of my sub-classes is named "Jewelry". Here I need to specify if the material is "gold" or "silver". The different material has a different value. (Gold = 2000, Silver= 700) Im not allowed to use Boolean. Im a big beginner so sorry for the "easy" question. You guys have any tips? much appreciated. Code:
public class Jewellery extends Valuable {
private int numberOfJewels;
private String material;
private double value;
public Jewellery(String name, int numberOfJewels, String material) {
super(name);
this.material = material.valueOf(material);
this.numberOfJewels = numberOfJewels;
}
public int getNumberOfJewels(){
return numberOfJewels;
}
public String getMaterial() {
return material;
}
public double getValue(){
return value;
}
public double getValuePlusVAT() {
return value();
}
public String toString(){
return getName() + " " + this.getMaterial() + " " + getValuePlusVAT();
}
}
The fast answer can be... use a strings SWITCH then.
The elaborated one is keep a enum with pairs material/value so is more flexible, maintainable and reusable around the application

Shallow Copy of Instance of Class within an ArrayList

I have an ArrayList which contains n instances of the class Boat. The class Boat has a number of methods which alter the instance variables of that boat.
For example:
public void Command(String command)
{
int inefficientwayofdoingthis=0;
if(command.equals("power on"))
{
inefficientwayofdoingthis++;
int x=1;
setpower(x);
System.out.println(name+" is on and is travelling in the direction of "+angle+" deg. with speed: "+ speed+"mph");
}
//...
The issue I am having is that this Command method should set the value of [instancename].power to 1.
The instances are contained in an ArrayList, data:
I am using the following code to alter the instances within the arraylist:
int numberinArray = whatever;
String theorder = "power on";
data.get(numberinArray).Command(theorder);
Each time I do so however, the command works and an output is produced, but subsequent commands do not seem to recognize that data.get(numberinArray).power should equal 1. I think I'm having a problem in that this is a deep copy of each instance of the class rather than a shallow copy. Would anyone have any suggestions on how to alleviate this issue?
if you want the power stay "attached" to the boat instance, this should be an instance variable. This could work in a way like this:
package com;
public class Boat {
private int power;
private String color;
Boat() {
// may want to initialize some values
this.setPower(0);
this.setColor("red");
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
then you could add some other methods like applyCommand(String command) in your example

My code doesn't work right? IF-statement multiple classes

I am relatively new to Java and as a newbie I have trouble understanding how the code works or executes. Most often I've figured out the answer in a minute or two, sometimes in an hour or two. However, I've been stuck for two days now and I'm afraid I can't work out the problem on my own.
The programming exercise that I'm currently working on is nearly finished, save for one bit that isn't working right: method setMaxSize doesn't seem to work the way it should. I've tried to edit the method addPlayer to make a IF-statement concerning the team's max size and current size. However, the method does not add players to the list, regardless of the fact that the team list is empty at the moment. What did I do wrong? Where's my mistake? How can I get the IF-statement in addPlayer to accept new players in an empty list while checking for the maximum possible number of players in team?
I'd appreciate any feedback I can get and I apologize if it's a noobish question, but I'm really running out of patience here. Also, it's not homework: it's a programming exercise I found online from a university website I found, but I have trouble finishing it.
I'm including the two class files and the main field.
import java.util.ArrayList;
public class Team {
private String name;
private ArrayList<Player> list = new ArrayList<Player>();
private int maxSize;
public Team (String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void addPlayer(Player player){
if (list.size() <= this.maxSize){
this.list.add(new Player(player.getName(), player.goals()));
}
}
public void printPlayers(){
for (Player player : list){
System.out.println(player.toString());
}
}
public void setMaxSize(int maxSize){
this.maxSize = maxSize;
}
public int size(){
return this.list.size();
}
public int goals(){
int goalSum = 0;
for (Player player : list){
goalSum+=player.goals();
}
return goalSum;
}
}
public class Main {
public static void main(String[] args) {
Team barcelona = new Team("FC Barcelona");
Player brian = new Player("Brian");
Player pekka = new Player("Pekka", 39);
barcelona.addPlayer(brian);
barcelona.addPlayer(pekka);
barcelona.addPlayer(new Player("Mikael", 1));
System.out.println("Total goals: " + barcelona.goals());
}
}
public class Player {
private String name;
private int goal;
public Player(String name){
this.name = name;
}
public Player(String name, int goal){
this.name = name;
this.goal = goal;
}
public String getName(){
return this.name;
}
public int goals(){
return this.goal;
}
public String toString(){
return "Player: " + this.name + ", goals " + this.goal;
}
}
You need to call setMaxSize before adding players to the team.
As you have said before, you are never calling setMaxSize, so there is maxSize is initially 0. Additionally, I suggest making setters and getters for all your data fields in each class, and making each field private.
For example, you have a setter for maxSize, but not getter. It doesn't make much sense to do one but not the other, right? You create better encapsulation and allow for future changes of your code much easier this way, and again it is better practice for future projects.

Java android multidimensional array (hash maybe) with string and nested class

I'm trying to track class stats for an android game I'm working on.
public static class characterClasses {
public String class_name;
public int base_hp;
public int base_attack;
public float base_defense;
}
I want to access these directly by name so I won't have to iterate over them repeatedly. From my research it looks like a hashmap or map would be what I need but everything I've seen is only for a single key/value pair. I need to access each stat value directly by class and value, something like
classList.get("warrior").get("base_hp");
Can someone point me in the right direction?
You are correct to think of using HashMap. You can use the characterClass String names as keys and the characterClasses as values. You can then use your getter methods to access your specific fields i.e.
classList.get("warrior").getBase_HP();
You could also forget maps entirely since these stats seem constant by using inheritance
public class Character {
int hp;
int attack;
int defense;
public Character (int hp, int attack, int defense) {
this.hp = hp;
this.attack = attack;
this.defense = defense;
}
public int getHP() {
return hp;
}
...
}
For your Character subclasses, you can preset those values in the constructor
public class Warrior extends Character {
public Warrior() {
super(2, 10, 8);
}
public int getHP() {
return super.getHP();
}
}
public class Wizard extends Character {
public Wizard() {
super(10, 3, 1);
}
public int getHP() {
return super.getHP();
}
}
This way all your Warrior and Wizard Objects will have the same stats that can be accessed any time simply by invoking their getters.

representing different kind of players in a class [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I am writing a class to represent cricket players. There are four types of cricket players
1 wicket player
2 batsman
3 bowler
4 allrounder
I'm not sure if I am representing the players in the right way
public class Player {
final static int WICKETPLAYER=1;
final static int BATSMAN=2;
final static int BOWLER=3;
final static int ALLROUNDER=4;
int currentbatting;
int bowlerbating;
int playertype;
public Player(int i,int currentbatting){
this.currentbatting=currentbatting;
playertype=i;
}
public String whatTypeOFplayer(){
switch(playertype){
case WICKETPLAYER:
return "wicketplayer" ;
case BATSMAN:
return " batsman";
case BOWLER:
return "bowler";
case ALLROUNDER:
return "allrounder";
default:
return "error";
}
}
}
First of all, you should use enums to represent the player types instead of ints, like
enum PlayerType {
WICKETPLAYER,
BATSMAN,
BOWLER,
ALLROUNDER
}
Then you could use the name() method to get a string representation of the PlayerType.
If there's more to the player types that just the name (e.g. different behaviour, methods etc.), you might consider creating subclasses of Player, like class WicketPlayer extends Player.
A third way would be to use composition and add components like PlayerBehaviour etc. to the basic player class.
I terms of complexity, I'd say no. 1 is the easiest, whereas no. 3 might be too complex for you right now. So you might try and either use no. 1 or no. 2, depending on your requirements.
You are likely to be better off with an enum and an EnumSet.
public Role {
WICKET_KEEPER, BATSMAN, BOWLER, FIELDER
}
public static final Set<Role> ALL_ROUNDER = EnumSet.allOf(Role.class);
private final EnumSet<Role> roles;
private Role position;
public Player(EnumSet<Role> roles) { this.role = roles; }
public void setPosition(Role role) { this.position = role; }
public String whatTypeOFplayer(){
return roles.equals(ALL_ROUNDER) ? "allrounder" : roles.toString();
}
BTW Its a Wicket Keeper not a Wicket Player http://www.cricketscotland.com/system/files/images/13_13.jpg
A better way is to inherit from the class Player, it will allow you a simpler treatment for each player and different behaviors for common actions. for example:
Player.java
public class Player {
int currentbatting;
int bowlerbating;
int playertype;
public Player(int i,int currentbatting){
this.currentbatting=currentbatting;
playertype=i;
}
public abstract String whatTypeOFplayer() {
return playertype;
}
}
WicketPlayer.java
public WicketPlayer extends Player {
public WicketPlayer(int i,int currentbatting){
super(int i,int currentbatting);
playertype = "wicketplayer";
}
}
Batsman.java
public Batsman extends Player {
public Batsman(int i,int currentbatting){
super(int i,int currentbatting);
playertype = "batsman";
}
}
And so on.
use Java Enums: http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
In this case - and because I smell homework - you should use one base class Player and a subclass for each player type.
Example:
public abstract class Player {
// some attributes and methods all players share
public abstract String whatTypeOfPlayer();
}
public WicketPlayer extends Player {
#Override
public String whatTypeOfPlayer() {
return "Wicket Player";
}
}
Bonus - then I'd use a factory to create players:
public PlayerFactory {
enum PlayerType {WICKETPLAYER, BATSMAN, BOWLER, ALLROUNDER}
public static Player createPlayer(PlayerType type, String name) {
switch(type) {
case WICKETPLAYER : return new WicketPlayer(name);
//...
}
}
}
If you are using Java 5+ use Enum Types Java Enum Types. According to Effective Java it's not a good practice to use a bunch of constants, instead use Enum.
public class Player {
public enum Role{
WICKETPLAYER,
BATSMAN,
BOWLER,
ALLROUNDER;
}
final int currentbatting;
final Role playerRole;
public Player(final Role role, final int currentbatting){
this.currentbatting=currentbatting;
this.playerRole=role;
}
public String whatTypeOFplayer(){
return this.playerRole.toString();
}
}

Categories