Cannot find symbol with mutators and accessors - java

I'm pretty knew to Java so I don't quite understand what I'm looking for when I'm trying to find errors in my program. I'm trying to create a player class for a game and I'm getting the "cannot find symbol" error. I did some research prior to asking this question but I don't understand the responses.
I get errors such as:
PlayerClass.java:51: cannot find symbol
symbol : variable getLevel
location: class PlayerClass
PlayerClass.setLevel(PlayerClass.getLevel + 1);
^
PlayerClass.java:51: setLevel(int) in PlayerClass cannot be applied to (<nulltype>)
PlayerClass.setLevel(PlayerClass.getLevel + 1);
^
PlayerClass.java:93: cannot find symbol
symbol : variable getName
location: class PlayerClass
if (name.equals(PlayerClass.getName))
^
3 errors
But here's the class:
import io.*;
//CLASS: Player
public class PlayerClass
{
//CLASS FIELDS: name, level, damage, health, kills
//CONSTRUCTORS:
private static int level, health, kills, damage;
private static String name;
//Default Constructor: IMPORT: None
public PlayerClass()
{
name = "Jeremy";
level = 1;
health = 100;
kills = 0;
}
//Alternate Constructor: IMPORT: inName
public PlayerClass(String inName)
{
name = inName;
level = 1;
health = 100;
kills = 0;
}
//Copy Constructor: IMPORT: inPlayer
public PlayerClass(PlayerClass inPlayer)
{
name = inPlayer.getName();
}
//MUTATORS:
//setName IMPORT: inName
public void setName(PlayerClass inPlayer)
{
name = inPlayer.getName();
}
//setLevel IMPORT: inLevel
public int setLevel(int inLevel)
{
PlayerClass.level = inLevel;
}
//levelUp IMPORT:inPlayer
public int levelUP(PlayerClass inPlayer)
{
PlayerClass.setLevel(PlayerClass.getLevel + 1);
}
//ACCESSORS:
//getName IMPORT: None EXPORT: name
public String getName()
{
return name;
}
//getLevel IMPORT: None EXPORT: level
public int getLevel()
{
return level;
}
//getHealth IMPORT: None EXPORT: health
public int getHealth()
{
return health;
}
//getKills IMPORT: None EXPORT: kills
public int getKills()
{
return kills;
}
//toString IMPORT: None EXPORT: playerStr
public String toString()
{
String playerStr;
playerStr = "Name: " + name + "Level: " + level + "Kills: " + kills;
return playerStr;
}
//equals IMPORT: inPlayer EXPORT: same
public boolean equals()
{
boolean same;
same = false;
if (name.equals(PlayerClass.getName))
{
same = true;
}
return same;
}
}

U have missed a parenthesis on getLevel() and getName() and have in mind that you have static fields. Also, you have put
//setLevel IMPORT: inLevel
public int setLevel(int inLevel)
{
PlayerClass.level = inLevel;
}
Where it should be void instead of an int if you want a setter, as well as levelUp() method.

to call a method getName on object player you would do player.getName(). You are missing parenthesis.
Semantically there are bunch of issues in your program.
Why are your fields static? They seem like instance variables. (Read the difference between static fields and instance fields)
Its not java convention to suffix class name with Class. In your case class name would simply be Person instead of PersonClass.
Your equals method is prone to throw NullpointerException
Two of your constructors have same code except for one statement. You should be able to factor out those using constructor chaining. (Read up about it)
I would write your code (using eclipse) as the following:
public class Player {
private int level, health, kills, damage;
private String name;
// Alternate Constructor: IMPORT: inName
public Player(String name, int level, int health, int kills) {
this.name = name;
this.level = level;
this.health = health;
this.kills = kills;
}
public Player() {
this("Jeremy", 1, 100, 0);
}
public Player(Player player) {
this.name = player.getName();
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int levelUP() {
this.setLevel(this.getLevel() + 1);
return this.level;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getKills() {
return kills;
}
public void setKills(int kills) {
this.kills = kills;
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// toString IMPORT: None EXPORT: playerStr
public String toString() {
String playerStr;
playerStr = "Name: " + this.name + "Level: " + this.level + "Kills: "
+ this.kills;
return playerStr;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Player other = (Player) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

Related

Problem with finding a string in an arrayList with objects [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have two classes called Pokemon.java and Move.java which contain methods for creating and modifying Pokemon and their moves. I've created all of the required methods, but I'm issues with the knowsMove method, specifically the one that requires a String instead of a Move. The method is supposed to see if a move with the given string is in a list of moves. When I tested out the method, it was returning true when it was supposed to be returning false, since there was no move with the string that I've given it.
Here is the code for the Pokemon.java class:
import java.util.ArrayList;
public class Pokemon
{
// Copy over your code for the Pokemon class here
// Private constants
private static final int MAX_HEALTH = 100;
private static final int MAX_MOVES = 4;
private String name;
private int health;
private int opponentHealth;
public static int numMovesForPokemon = Move.getNumOfMoves();
private int doesListContainName = 0;
private Move move;
private ArrayList<Move> moveListForPokemon = new ArrayList<Move>();
private String pokemonImage;
// Write your Pokemon class here
public Pokemon(String theName, int theHealth)
{
name = theName;
if(theHealth <= MAX_HEALTH)
{
health = theHealth;
}
}
public Pokemon(String name, String image)
{
this.name = name;
health = 100;
pokemonImage = image;
}
public Pokemon(String theName)
{
name = theName;
}
public void setImage(String image)
{
pokemonImage = image;
}
public String getImage()
{
return pokemonImage;
}
public String getName()
{
return name;
}
public int getHealth()
{
return health;
}
public void setHealth(int health)
{
this.health = health;
}
public boolean hasFainted()
{
if(health <= 0)
{
return true;
}
else
{
return false;
}
}
public boolean canLearnMoreMoves()
{
if(numMovesForPokemon < 4)
{
return true;
}
else
{
return false;
}
}
public boolean learnMove(Move other)
{
if(canLearnMoreMoves())
{
moveListForPokemon.add(other);
numMovesForPokemon++;
return true;
}
else
{
return false;
}
}
public void forgetMove(Move other)
{
moveListForPokemon.remove(other);
}
public ArrayList<Move> displayList()
{
return moveListForPokemon;
}
public boolean knowsMove(Move move)
{
if(moveListForPokemon.contains(move))
{
return true;
}
else
{
return false;
}
}
public boolean knowsMove(String moveName)
{
for(Move m : moveListForPokemon)
{
if(m.getName() != null && m.getName().contains(moveName))
{
doesListContainName = 1;
}
}
if(doesListContainName == 1)
{
return true;
}
else
{
return false;
}
}
public boolean attack(Pokemon opponent, Move move)
{
if(knowsMove(move))
{
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
opponent.setHealth(opponentHealth);
return true;
}
else
{
return false;
}
}
public boolean attack(Pokemon opponent, String moveName)
{
if(knowsMove(moveName))
{
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
opponent.setHealth(opponentHealth);
return true;
}
else
{
return false;
}
}
public String toString()
{
return pokemonImage + "\n" + name + " (Health: " + health + " / " + MAX_HEALTH + ")";
}
// Add the methods specified in the exercise description
}
Here is the code for the Move.java class:
import java.util.ArrayList;
public class Move
{
// Copy over your code for the Move class here
private static final int MAX_DAMAGE = 25;
private String name;
private int damage;
public static int numMoves;
private ArrayList<Move> moveList = new ArrayList<Move>();
public Move(String theName, int theDamage)
{
name = theName;
if(theDamage <= MAX_DAMAGE)
{
damage = theDamage;
}
}
public String getName()
{
return name;
}
public int getDamage()
{
return damage;
}
public static int getNumOfMoves()
{
return numMoves;
}
public ArrayList<Move> getList()
{
return moveList;
}
public String toString()
{
return name + " (" + damage + " damage)";
}
// Add an equals method so we can compare Moves against each other
public boolean equals(Move other)
{
if(name.equals(other.getName()))
{
return true;
}
else
{
return false;
}
}
}
Finally, here is the code for PokemonTester.java where I test out the methods:
public class PokemonTester extends ConsoleProgram
{
private PokemonImages images = new PokemonImages();
public void run()
{
// Test out your Pokemon class here!
Pokemon p1 = new Pokemon("Charrizard", 100);
Pokemon p2 = new Pokemon("Pikachu", 100);
Move m1 = new Move("Flamethrower", 20);
Move m2 = new Move("Fire Breath", 15);
p1.learnMove(m1);
System.out.println("Pokemon knows move 1: " + p1.knowsMove(m1));
System.out.println("Pokemon knows move 1 (String): " + p1.knowsMove("Flamethrower"));
System.out.println("Pokemon knows move 2 (String): " + p1.knowsMove("Fire Breath"));
System.out.println("Pokemon knows move 2: " + p1.knowsMove(m2));
System.out.println("Move 1 Damage: " + m1.getDamage());
System.out.println("Pokemon attack opponent with move 1: " + p1.attack(p2, m1));
System.out.println("Opponent health: " + p2.getHealth());
}
}
The doesListContainName should not be a class variable and instead be a local variable for the "knowsMove" method. The variable doesListContainName is initialized as 0, then the test called "knowsMove" with a move that it does know, so the doesListContainName variable is set to 1. The test then calls knowsMove with an unknown move but the doesListContainName is still 1 so it returns true as well.

Creating a Pokémon class in Java

I have a Java project that requires me to have two classes called: Pokemon.java and Move.java so I can add new Pokemon and their moves. I’ve already written all of the methods that were required for the project but I’m having issues storing and modifying the moves, specifically the forgetMove method in the Pokemon class.
Here’s the code for Pokemon.java:
public class Pokemon
{
// Private constants
private static final int MAX_HEALTH = 100;
private static final int MAX_MOVES = 4;
private String name;
private int health;
private Move move;
// Write your Pokemon class here
public Pokemon(String theName, int theHealth)
{
name = theName;
if(theHealth <= MAX_HEALTH)
{
health = theHealth;
}
}
public String getName()
{
return name;
}
public int getHealth()
{
return health;
}
public boolean hasFainted()
{
if(health <= 0)
{
return true;
}
else
{
return false;
}
}
public boolean canLearnMoreMoves()
{
if(Move.getNumOfMoves() < 4)
{
return true;
}
else
{
return false;
}
}
public boolean learnMove(Move move)
{
if(canLearnMoreMoves())
{
this.move = move;
return true;
}
else
{
return false;
}
}
public void forgetMove(Move other)
{
if(Move.equals(other))
{
move -= other;
}
}
public String toString()
{
return name + " (Health: " + health + " / " + MAX_HEALTH + ")";
}
}
and here is the code for Move.java:
public class Move
{
// Copy over your Move class into here
private static final int MAX_DAMAGE = 25;
private static String name;
private static int damage;
public static int numMoves;
public Move(String theName, int theDamage)
{
name = theName;
if(theDamage <= MAX_DAMAGE)
{
damage = theDamage;
}
numMoves++;
}
public static String getName()
{
return name;
}
public static int getDamage()
{
return damage;
}
public static int getNumOfMoves()
{
return numMoves;
}
public String toString()
{
return name + " (" + damage + " damage)";
}
// Add an equals method so we can compare Moves against each other
public static boolean equals(Move other)
{
if(name.equals(other.getName()))
{
return true;
}
else
{
return false;
}
}
}
Here is the code for PokemonTester.java:
public class PokemonTester extends ConsoleProgram
{
public void run()
{
Pokemon p1 = new Pokemon("Charrizard", 100);
Move m1 = new Move("Flamethrower", 90);
System.out.println(p1);
System.out.println(m1);
}
}
This seems like it might be homework so I won't give you a full implementation.
If you are simply filling out the methods required for the Pokemon and Move class, I would start by reconsidering the way you are storing moves.
The getNumOfMoves provides a hint that your Pokemon class should store more than one move, a common way to do this is with arrays or lists.
If you have stored your moves in a list, the forgetMove function may look like this:
public void forgetMove(Move other){
moves.remove(other);
}

Guice AssistedInject can not find matching constructor

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)
);

Java static/nonstatic method

I started working on my first java project, which is a basic RPG, and I have a question regarding the spells. I have an abstract class named Character, which is extended by some subclasses (like Fighter, Mage etc.). Only spellcasters can cast spells. Regarding Spells - I have a class named Spell that describes a spell (it's name, it's effect, mana etc.). All the spells are stored in SpellsList class that has a spellsList list (objects of class Spell). I have an Effect class (very plausible that it will become an interface) that has some effects like "damage" and "heal", but I don't make use of that for the meanwhile, I just want to test that what I have works.
My problem is that Mage's methods addToSpellBook and showSpellBook give a compiler error: java can't find symbol: method addToSepllBook, location: variable hero of type Game.Character. also for showSpellBook. Why and how to fix it ?
(The problem is probably in Mage/Spell/SpellsList class, and not Character which is long, so it's less intimidating :) )
public class Game {
public static void main(String[] args) throws IOException {
CharacterCreator heroCreator = new CharacterCreator();
CharacterCreator.showAllClasses();
Scanner sc = new Scanner(System.in);
int scan = sc.nextInt();
String chosenClass = CharacterCreator.getCharacterClass(scan);
Character hero = CharacterCreator.createCharacter(chosenClass);
try {
hero.displayCharacter();
}catch (Exception e){
System.out.println("Wrong input");
}
if (hero.getCharacterClass().equals("Mage")){
hero.addToSpellBook("Fireball");
hero.showSpellBook();
}
}
}
public class CharacterCreator {
public static Character createCharacter(String chosenClass) {
Character hero = null;
System.out.println("Choose Name:");
Scanner nameIn = new Scanner(System.in);
String name = nameIn.next();
switch (chosenClass) {
case "Fighter":
return new Fighter(name);
case "Rogue":
return new Rogue(name);
case "Mage":
return new Mage(name);
case "Cleric":
return new Cleric(name);
case "def":
System.out.println("Wrong input");
return null;
default:
return null;
}
}
public static void showAllClasses(){
System.out.println("Choose a character: ");
System.out.println("1. Fighter");
System.out.println("2. Rogue");
System.out.println("3. Mage");
System.out.println("4. Cleric");
}
public static String getCharacterClass(int scan){
String classIn;
switch (scan) {
case 1:
classIn = "Fighter";
break;
case 2:
classIn = "Rogue";
break;
case 3:
classIn = "Mage";
break;
case 4:
classIn = "Cleric";
break;
default:
System.out.println("Enter again");
classIn = "def";
}
return classIn;
}
}
abstract public class Character {
private String name;
private String characterClass;
private int level;
private int hp;
private int currentHp;
private int armorClass;
private long xp;
/*private int BAB; /*Base attack bonus*/
private int strength;
private int constitution;
private int dexterity;
private int intelligence;
private int wisdom;
private int charisma;
protected Character(String name){
setName(name);
setCharacterClass("Class");
setLevel(1);
setStrength(10);
setConstitution(10);
setDexterity(10);
setIntelligence(10);
setWisdom(10);
setCharisma(10);
setHp(0);
setCurrentHp(getHp());
setArmorClass(10);
setXp(0);
}
void displayCharacter() throws IOException{
System.out.print("\n\n\n");
System.out.println("Name: " + getName());
System.out.println("Class: " + getCharacterClass());
System.out.println("Level: " + getLevel());
System.out.println("HP: " + getHp());
System.out.println("Current HP: " + getCurrentHp());
System.out.println("Armor Class: " + getArmorClass());
System.out.println("***************");
System.out.println("Attributes: ");
System.out.println("Strength: " + getStrength());
System.out.println("Constitution: " + getConstitution());
System.out.println("Dexterity: " + getDexterity());
System.out.println("Intelligence: " + getIntelligence());
System.out.println("Wisdom: " + getWisdom());
System.out.println("Charisma: " + getCharisma());
System.out.println("***************");
System.out.println("XP: " + getXp());
}
public int getModifier(int number){
int mod = (int)((number -10)/2);
return mod;
}
public String getName() { return name; }
public String getCharacterClass() { return characterClass; }
public int getLevel() { return level; }
public int getHp() { return hp; }
public int getCurrentHp() { return currentHp; }
public int getArmorClass() { return armorClass; }
public int getStrength(){ return strength; }
public int getConstitution(){ return constitution; }
public int getDexterity(){ return dexterity; }
public int getIntelligence(){ return intelligence; }
public int getWisdom(){ return wisdom; }
public int getCharisma(){ return charisma;}
public long getXp(){ return xp;}
protected void setName(String Name) { name = Name; }
protected void setCharacterClass(String characterClass) { this.characterClass = characterClass; }
protected void setLevel(int lvl){ level = lvl; }
protected void setHp(int hitPoints){ hp = hitPoints; }
protected void setCurrentHp(int curHp){ currentHp = curHp; }
protected void setArmorClass(int ac){ armorClass = ac; }
protected void setStrength(int str){ strength = str; }
protected void setConstitution(int con){ constitution = con; }
protected void setDexterity( int dex) { dexterity = dex; }
protected void setIntelligence(int intel){ intelligence = intel; }
protected void setWisdom(int wis){ wisdom = wis; }
protected void setCharisma(int cha){charisma = cha; }
protected void setXp(int XP){xp = XP; }
}
public class Mage extends Character {
private List<Spell> spellBook;
public Mage(String name){
super(name);
setName(name);
setCharacterClass("Mage");
setLevel(1);
setStrength(10);
setConstitution(10);
setDexterity(14);
setIntelligence(16);
setWisdom(14);
setCharisma(10);
setHp((int) (4 + getModifier(getConstitution())));
setCurrentHp(getHp());
setArmorClass(10 + getModifier(getDexterity()));
spellBook = null;
}
void addToSpellBook(String spellName){
Spell newSpell;
newSpell = SpellsList.getSpell(spellName);
spellBook.add(newSpell);
}
void showSpellBook(){
for (Iterator<Spell> iter = spellBook.iterator(); iter.hasNext(); ) {
Spell spell = iter.next();
if (spellBook.equals(spell.getSpellName())) {
System.out.println("Spell name: " + spell.getSpellName());
System.out.println("Spell effect: " + spell.getEffect());
}
}
}
}
public class Spell {
private String name;
private int spellLevel;
private String effect;
private int manaCost;
private int duration;
Spell(String name, int spellLevel, String effect, int manaCost, int duration){
this.name = name;
this.spellLevel = spellLevel;
this.effect = effect;
this.manaCost = manaCost;
this.duration= duration;
}
void castSpell(String spellName, Character hero, Character target){
try {
Spell spell = SpellsList.getSpell(spellName);
System.out.println("You casted: " + spellName);
System.out.println("Spell effect: " + spell.effect);
}
catch (Exception e){
System.out.println("No such spell");
}
}
String getSpellName(){ return name; }
int getSpellLevel() {return spellLevel; }
String getEffect(){ return effect; }
int getManaCost(){
return manaCost;
}
int getDuration() { return duration; }
}
public class SpellsList {
static List<Spell> spellsList = new ArrayList<Spell>();
static
{
spellsList.add(new Spell("Fireball", 3, "damage", 5,0 ));
spellsList.add(new Spell("Ice Storm", 4, "damage", 8, 0));
spellsList.add(new Spell("Heal", 2, "heal", 4, 0));
}
static Spell getSpell(String spellName) {
try {
for (Iterator<Spell> iter = spellsList.iterator(); iter.hasNext(); ) {
Spell spell = iter.next();
if (spellName.equals(spell.getSpellName())) {
return spell;
}
}
} catch (Exception e){
System.out.println(spellName + " haven't been found in spells-list");
return null;
}
return null;
}
}
hero is of type Character. You should cast it to Mage. or add addToSpellBook in Character class and override it in Mage class. Something like:
if(hero instanceof Mage)
((Mage) hero).addToSpellBook();
There is a difference between the type of variables when compiling and their class during execution. The problem is that your hero variable is not of type Mage but of type Character and only has access to methods available to any Character.
The compiler also doesn't notice your logic in attempting to make sure hero is an instance of Mage. To tell it you know you have Mage and want to use Mage methods you need to cast.
Your way of verifying is okay, but I would advise using theinstanceof keyword.
if(hero instanceof Mage) {
((Mage)hero).addToSpellBook("Fireball");
((Mage)hero).showSpellBook();
}
You call the methodes addToSpellBook and showSpellBook on the class Character, but you have no methodes with this names in your class Character.

PrimeAgeChecker only returning false

My PrimeAgeChecker is returning false for every age even those that are prime and I can not seem to figure out why this is. I am new to programming and help would be appreciated. Could anyone point me in the right direction?
public class Employee {
// fields
String name;
int age;
Department department;
PrimeAgeChecker checks;
// constructors
public Employee(Department department, String name, int age) {
this.name = name;
this.age = age;
this.department = department;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Department getDepartment() {
return department;
}
public boolean getChecker(){
return PrimeAgeChecker.isPrime;
}
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append(getDepartment() + " ");
sb.append("\t");
sb.append(getName());
sb.append("\t");
sb.append(getAge());
sb.append("\t");
sb.append(getChecker());
return sb.toString();
}
}
public class PrimeAgeChecker {
static int ages;
public static boolean isPrime = false;
PrimeAgeChecker(Employee age) {
ages = age.getAge();
}
public boolean check() {
if ((ages % 2 == 0) || (ages == 2))
{
isPrime = true;
}
return isPrime;
}
}
Fixed Solution
public boolean getChecker(){
PrimeAgeChecker primeAgeChecker = new PrimeAgeChecker();
return primeAgeChecker.isPrime(getAge());
}
public class PrimeAgeChecker {
static int ages;
public boolean isPrime;
public static void getAge(Employee e){
ages = e.getAge();
}
boolean isPrime(int ages) {
if (ages%2==0) return false;
for(int i=3;i*i<=ages;i+=2) {
if(ages%i==0)
return isPrime = false;
}
return isPrime = true;
}
}
The problem is that when you call getChecker(), you are returning PrimeAgeChecker.isPrime which returns the value of the static variable isPrime. isPrime is declared to be false, which causes your PrimeAgeChecker to always return false.
What you need to do is create an instance of PrimeAgeChecker, passing in the age then call the check method of PrimeAgeChecker.
Your getChecker method could look something like this:
public boolean getChecker(int age){
PrimeAgeChecker primeAgeChecker = new PrimeAgeChecker(age);
return primeAgeChecker.check();
}
Keep in mind, as others have mentioned, your logic behind checking whether the age is prime is also flawed.

Categories