Java OOD and code duplication - java

I started creating a basic roleplaying game, and now I work on the basics. I have a code duplication for creating new characters and for existed character, which is a very bad things. I'll explain my problem - At the beginning a player can choose a Character Class (like fighter) by calling using CharacterCreator. I have a Character class that describes all the information regarding the character. I also have an abstract class named CharacterClass that describes specific attributes and other stuff of character classes (like Fighter, not java class). CharacterClass has some subclasses (like Fighter, Mage etc.). The code works, but has a bad design.
How can I get rid of the code duplication of Character and CharacterClass? Should I change the design?
public class Game {
public static void main(String[] args) {
Character hero = CharacterCreator.CharacterCreator();
}
}
public class CharacterCreator {
public static Character CharacterCreator() {
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");
Scanner sc = new Scanner(System.in);
int scan = sc.nextInt();
String choice = getCharacterClass(scan);
System.out.println("Choose Name:");
Scanner nameIn = new Scanner(System.in);
String name = nameIn.next();
CharacterClass chosenClass = null;
Character hero = null;
switch (choice){
case "Fighter":
chosenClass = new Fighter();
break;
case "Rogue":
chosenClass = new Rogue();
break;
case "Mage":
chosenClass = new Mage();
break;
case "Cleric":
chosenClass = new Cleric();
break;
}
try {
hero = new Character(name, chosenClass);
System.out.println("A hero has been created");
hero.displayCharacter();
} catch (Exception e){
System.out.println("There was a problem assigning a character class");
}
return hero;
}
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;
}
}
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;
Character(String name, CharacterClass chosenClass){
this.name = name;
this.characterClass = chosenClass.getCharacterClass();
level = chosenClass.getLevel() ;
hp = ( chosenClass.getHp() + getModifier( chosenClass.getConstitution() ) );
currentHp = hp;
setArmorClass(10 + getModifier( + chosenClass.getDexterity()));
strength = chosenClass.getStrength();
constitution = chosenClass.getConstitution();
dexterity = chosenClass.getDexterity();
intelligence = chosenClass.getIntelligence();
wisdom = chosenClass.getWisdom();
charisma = chosenClass.getCharisma();
xp = 0;
}
void displayCharacter() throws IOException {
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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("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 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; }
}
abstract class CharacterClass {
private String characterClass;
private int level;
private int hp;
private int strength;
private int constitution;
private int dexterity;
private int intelligence;
private int wisdom;
private int charisma;
protected CharacterClass(){
setCharacterClass("Character Class");
setLevel(1);
setHp(10);
setStrength(10);
setConstitution(10);
setDexterity(10);
setIntelligence(10);
setWisdom(10);
setCharisma(10);
}
public String getCharacterClass() { return characterClass; }
public int getLevel() { return level; }
public int getHp() { return hp; }
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; }
protected void setCharacterClass(String characterClass){ this.characterClass = characterClass; }
protected void setLevel(int lvl){ level = lvl; }
protected void setHp(int hitPoints){ hp = hitPoints; }
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; }
}
class Fighter extends CharacterClass {
Fighter(){
setCharacterClass("Fighter");
setLevel(1);
setHp(10);
setStrength(14);
setConstitution(16);
setDexterity(14);
setIntelligence(10);
setWisdom(10);
setCharisma(10);
}
}

suggestions:
CharacterCreator.CharacterCreator(). Method should be verb and describe action, i.e createCharacter
look ad design pattern Factory. Your Creator is 'Factory'. The method 'createCharacter' should take parameter characterType. That means, that getting info from System.in should be done in class who invoke that method.
Add enum for characterClass with mapping to numbers (look to inner map in enum).

Whilst this is not a direct solution to your problem, this should help you in the long run. When it comes to games, especially RPG genre, where you have lots of objects which seem to be similar yet different, inheritance isn't best foundation for design. On top of the example you have, one will also have problems when designing consumable items / weapons / gear / NPC, etc. This means you end up with having duplicate code in many classes simply because using abstract class would mean all subclasses have same behavior, but this is not true.
A better approach in this case is to avoid inheritance and use ECS. This means everything is a type of Entity. In order to add some "functionality" to an entity you would use Component types. For example, items don't have HP property, but say when dropped on the ground, they can be attacked and destroyed. Meaning we need to add a dynamic property to it. We can do that as follows:
entityItem.addComponent(new HPComponent(50));
This will allow other systems like Attack/Damage to "see" that the entity has HP component and can be attacked.
This is just a tiny example of ECS and there's lots more to it. I'd suggest reading more about it, as this will make game development design (for most games) significantly smoother.

Related

How to use polymorphism to access a method inside a subclass that is not defined in the super class using a reference variable of a superclass

If i have 2 classes the first one is BasicHamburger
public class BasicHamburger {
private String breadRollType;
private String meat;
private boolean lettuce;
private boolean tomato;
private boolean carrot;
private boolean cheese;
private int numberOfAdditions;
private int price;
public BasicHamburger(String breadRollType , String meat ,int price){
this.breadRollType = breadRollType;
this.meat = meat;
this.price = price;
lettuce = false;
tomato = false;
carrot = false;
cheese = false;
numberOfAdditions = 0;
}
public void addLettuce(){
lettuce = true;
incrementNumberOfAdditions();
}
public void addTomato(){
tomato = true;
incrementNumberOfAdditions();
}
public void addCarrot(){
carrot = true;
incrementNumberOfAdditions();
}
public void addCheese(){
cheese = true;
incrementNumberOfAdditions();
}
public int getNumberOfAdditions(){
return numberOfAdditions;
}
protected int incrementNumberOfAdditions(){
return ++numberOfAdditions;
}
public boolean isLettuce() {
return lettuce;
}
public boolean isTomato() {
return tomato;
}
public boolean isCarrot() {
return carrot;
}
public boolean isCheese() {
return cheese;
}
public int getBasicHamburgerPrice(){
return price;
}
public int getLettucePrice(){
return 20;
}
public int getTomatoPrice(){
return 15;
}
public int getCheesePrice(){
return 40;
}
public int getCarrotPrice(){
return 10;
}
public int getTotalBasicHamburgerPrice(){
if(isCarrot()){
price = price + 10;
}
if(isCheese()){
price = price + 40;
}
if(isTomato()){
price = price + 15;
}
if(isLettuce()){
price = price + 20;
}
return price;
}
public void displayBurgerDetailsWithPrices(){
if(isCarrot()){
System.out.println("Carrot addition = "+getCarrotPrice());
}
if(isCheese()){
System.out.println("Cheese addition = "+getCheesePrice());
}
if(isTomato()){
System.out.println("Tomato addition = "+getTomatoPrice());
}
if(isLettuce()){
System.out.println("Lettuce addition = "+getLettucePrice());
}
System.out.println("Basic Hamburger Total Price Without Additions = "+getBasicHamburgerPrice());
System.out.println("Basic Hamburger Total Price After Additions= "+getTotalBasicHamburgerPrice());
}
}
the second class is HealthyBurger
public class HealthyBurger extends BasicHamburger{
private boolean onion;
private boolean bacon;
public HealthyBurger(){
super("Brown Rye ","Mutton",30);
onion = false;
bacon = false;
}
public boolean isOnion() {
return onion;
}
public boolean isBacon() {
return bacon;
}
public void addOnion(){
onion = true;
incrementNumberOfAdditions();
}
public void addBacon(){
bacon = true;
incrementNumberOfAdditions();
}
public int getOnionPrice(){
return 15;
}
public int getBaconPrice(){
return 20;
}
#Override
public int getTotalBasicHamburgerPrice() {
int newPrice = super.getTotalBasicHamburgerPrice();
if(isBacon()){
newPrice += 20;
}
if(isOnion()){
newPrice +=15;
}
return newPrice;
}
#Override
public void displayBurgerDetailsWithPrices() {
if(isCarrot()){
System.out.println("Carrot addition = "+getCarrotPrice());
}
if(isCheese()){
System.out.println("Cheese addition = "+getCheesePrice());
}
if(isTomato()){
System.out.println("Tomato addition = "+getTomatoPrice());
}
if(isLettuce()){
System.out.println("Lettuce addition = "+getLettucePrice());
}
if(isOnion()){
System.out.println("Onion addition = "+getOnionPrice());
}
if(isBacon()){
System.out.println("Bacon addition = "+getBaconPrice());
}
System.out.println("Healthy Hamburger Total Price Without Additions = "+getBasicHamburgerPrice());
System.out.println("Healthy Hamburger Total Price After Additions= "+getTotalBasicHamburgerPrice());
}
}
in the main i have written this code
public class Main {
public static void DisplayBurger(BasicHamburger burger){
burger.displayBurgerDetailsWithPrices();
}
public static void main(String[] args) {
BasicHamburger ham1 = new BasicHamburger("x","beef",20);
ham1.addCarrot();
ham1.addCheese();
ham1.addLettuce();
ham1.addTomato();
HealthyBurger ham2 = new HealthyBurger();
ham2.addOnion();
ham2.addBacon();
BasicHamburger test = ham2;
DisplayBurger(test);
}
}
My confusion is the test variable can access displayBurgerDetailsWithPrices() function inside HealthyBurger class and can call the isOnion which is inside that function. Whereas if i decided to write that code inside the main i can not access the isOnion() function.
BasicHamburger newBurger = new HealthyBurger();
newBurger.isOnion();
To make the question clear and right to the point , why accessing a function inside a subclass through a overriden function is possible whereas accessing that function directly is not possible when using a variable of the superclass?
BasicHamburger newBurger = new HealthyBurger();
boolean onion = false;
if(newBurger instanceof HealthyBurger)
onion = ((HealthyBurger).isOnion());
To make the question clear and right to the point, why accessing a function inside a subclass through an overridden function is possible whereas accessing that function directly is not possible when using a variable of the superclass?
It calles Polymophism. The object reference BasicHamburger newBurger refers to the instance of class BasicHamburger or any of its children. It means that by default you have access only to the methods declared in BasicHamburger or any of its parent. If you want to call the children's method, you have to cast this reference to the required type.
I would redesign your code, because in general case if you use casting, then it looks like a design problem (repeat: in general; sometimes it really needed).
public abstract class Burger {
protected final String breadRollType;
protected final String meat;
protected final int basePrice;
protected final Set<Ingredient> ingredients;
protected Burger(String breadRollType, String meat, int basePrice, Set<Ingredient> ingredients) {
this.breadRollType = breadRollType;
this.meat = meat;
this.basePrice = basePrice;
this.ingredients = ingredients == null || ingredients.isEmpty() ? Set.of() : Set.copyOf(ingredients);
}
public final int getBasePrice() {
return basePrice;
}
protected int getIngredientsPrice() {
return ingredients.stream()
.map(Ingredient::getPrice)
.mapToInt(i -> i)
.sum();
}
public int getTotalPrice() {
return basePrice + getIngredientsPrice();
}
public final int getTotalIngredients() {
return ingredients.size();
}
public final boolean hasIngredient(Ingredient ingredient) {
return ingredient != null && ingredients.contains(ingredient);
}
public void printDetailsWithPrices() {
System.out.println(breadRollType + ' ' + meat);
System.out.println("----");
System.out.println("Basic price: " + basePrice);
System.out.println("Ingredients price: " + getIngredientsPrice());
ingredients.forEach(ingredient -> System.out.format("-> %s price: %d\n",
ingredient.getTitle(), ingredient.getPrice()));
System.out.println("Total price: " + getTotalPrice());
}
protected interface Ingredient {
String getTitle();
int getPrice();
}
}
public class HealthyBurger extends Burger {
public HealthyBurger(String breadRollType, String meat, int basePrice, Set<Burger.Ingredient> ingredients) {
super(breadRollType, meat, basePrice, ingredients);
}
public enum Ingredient implements Burger.Ingredient {
ONION("Onion", 15),
BACON("Bacon", 20);
private final String title;
private final int price;
Ingredient(String title, int price) {
this.title = title;
this.price = price;
}
#Override
public String getTitle() {
return title;
}
#Override
public int getPrice() {
return price;
}
}
}
public class PopularBurger extends Burger {
protected PopularBurger(String breadRollType, String meat, int basePrice, Set<Burger.Ingredient> ingredients) {
super(breadRollType, meat, basePrice, ingredients);
}
public enum Ingredient implements Burger.Ingredient {
LETTUCE("Lettuce", 20),
TOMATO("Tomato", 25),
CARROT("Carrot", 10),
CHEESE("Cheese", 40);
private final String title;
private final int price;
Ingredient(String title, int price) {
this.title = title;
this.price = price;
}
#Override
public String getTitle() {
return title;
}
#Override
public int getPrice() {
return price;
}
}
}
public static void main(String... args) {
PopularBurger popularBurger = new PopularBurger("x", "beef", 20,
Set.of(PopularBurger.Ingredient.CARROT,
PopularBurger.Ingredient.CHEESE,
PopularBurger.Ingredient.LETTUCE,
PopularBurger.Ingredient.TOMATO));
HealthyBurger healthyBurger = new HealthyBurger("Brown Rye", "Mutton", 30,
Set.of(HealthyBurger.Ingredient.ONION,
HealthyBurger.Ingredient.BACON));
PopularBurger one = popularBurger;
one.printDetailsWithPrices();
System.out.println();
HealthyBurger two = healthyBurger;
two.printDetailsWithPrices();
System.out.println();
boolean withOnion = two.hasIngredient(HealthyBurger.Ingredient.ONION);
System.out.println(withOnion);
}
x beef
----
Basic price: 20
Ingredients price: 95
-> Cheese price: 40
-> Carrot price: 10
-> Lettuce price: 20
-> Tomato price: 25
Total price: 115
Brown Rye Mutton
----
Basic price: 30
Ingredients price: 35
-> Onion price: 15
-> Bacon price: 20
Total price: 65
true

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

Returning values from class A to class B and then to Main class?

I am programming a simple character creation program to study classes and Java programming.
The code is work in progress and not runnable because I don't know how to make it work.
My problem is that I don't know how to properly return details/info/values from another class to another class and then to the main class.
What I am trying to solve is how to get the information stored in weapon.java and characteristic.java , so that I can use them in player.java. So lets say a user inputs 1 for warrior. Then I need to get the information for Weapon and Characteristics from their own classes, and return this information for SetClass Method in Player.java.
In short something like:
If user input = 1 => classType is Warrior => weaponType is Sword
Anyways
Here is my code so far:
The main program:
import java.util.*;
public class characterCreationProgam {
private static Scanner input = new Scanner(System.in);
public static void main1(String[] args) {
try {
System.out.println("Welcome to the super simple character creator ");
System.out.println("Choose class: 1: Warrior 2: Wizard 3: Rogue 4: Healer ");
int class = input.nextInt();
// creating new OOP
Player newCharacter = new Player(class);
newCharacter.setClass(class);
System.out.println("New character has been made: ");
newCharacter.printPlayer();
System.out.println("Print character stats? 1: Yes 2: No ");
int answer = input.nextInt();
if (answer == 1) {
newCharacter.printClass();
} else if (answer == 2) {
return;
}
System.out.println("Print weapon stats? 1: Yes 2: No ");
int answer2 = input.nextInt();
if (answer2 == 1) {
newCharacter.printWeapon();
} else if (answer2 == 2) {
return;
}
System.out.println("Shutting down the program.");
System.exit(1);
} catch (Exception e) {
System.out.println("Error! Program closing.");
System.exit(1);
}
}
}
Player.Java class
public class Player {
private int class;
private String sex;
private int age;
private int weapon;
public Player(int class) {
this.class = class;
this.sex = "";
this.age = 0;
this.weapon = 0;
}
// Method for setting the class
public void setClass(int class) {
if (class == 1) { // Warrior
// something here to return proper character class and weapon
// from their own class files
this.sex = "Male";
this.age = 45;
} else if (class == 2) { // Wizard
// something here to return proper character class and weapon
// from their own class files
this.sex = "Female";
this.age = 30;
} else if (class == 3) { // Rogue
// something here to return proper character class and weapon
// from their own class files
this.sex = "Female";
this.age = 25;
} else if (class == 4) { // healer
// something here to return proper character class and weapon
// from their own class files
this.sukupuoli = "Male";
this.age = 21;
} else {
System.out.println("Unkown class selection. ");
}
}
// Method to return/print character info
public void printPlayer() {
System.out.println("class: " + this.class + "\nGender: "
+ this.sex + "\nAge: " + this.age + "\nWeapon: "
+ this.weapon);
}
// Method to return/print class info
public void printClass() {
// Something here to return classInfo from CharacterClass.Java
}
// Method to return/print weapon info
public void printWeapon() {
// Something here to return weaponInfo from Weapon.Java
}
}
Characterstics.Java class
public class Class {
private String className;
private int classLevel;
private String specialSkills;
public Class(String name, int level, String skills) {
this.className = name;
this.classLevel = level;
this.specialSkills = skills;
}
public void classType() {
if () { // Don't know what to put in here
this.className = "Warrior";
this.classLevel = 90;
this.specialSkills = "Damage reduction";
// Something to set correct weapon to this classType from
// weapon.java
} else if () { // Don't know what to put in here
this.className = "Wizard";
this.classLevel = 75;
this.specialSkills = "Magic ";
// Something to set correct weapon to this classType from
// weapon.java
} else if () { // Don't know what to put in here
this.className = "Rogue";
this.classLevel = 55;
this.specialSkills = "Dodge";
// Something to set correct weapon to this classType from
// weapon.java
} else if () { // Don't know what to put in here
this.className = "Healer";
this.classLevel = 69;
this.specialSkills = "Healing";
// Something to set correct weapon to this classType from
// weapon.java
}
}
// Method to return characters details.
public void characterInfo() {
System.out.println("\nClass: " + this.className + "\nLevel: "
+ this.classLevel + "\nSkills: " + this.specialSkills);
}
}
and finally...
Weapon.Java class
public class Weapon {
// Luokan
private int damage;
private String type;
private String bonus;
public Weapon() {
this.damage = 0;
this.type = "";
this.bonus = "";
}
public void weaponType() {
if () { // Don't know what to put in here, class is warrior
this.type = "Sword";
this.damage = 75;
this.bonus = "Armor penetration";
} else if () { // Don't know what to put in here, class is wizard
this.type = "Staff";
this.damage = 35;
this.bonus = "Spell casting";
} else if () { // Don't know what to put in here, class is rogue
this.type = "Daggers";
this.damage = 55;
this.bonus = "Poisoning enemies";
} else if () { // Don't know what to put in here, class is healer
this.type = "Hammer";
this.damage = 85;
this.bonus = "Stunning enemies";
}
}
// Method to print weapon details.
public void weaponInfo() {
System.out.println("Weapon type: " + this.type + "\nDamage: "
+ this.damage + "\nBonus: " + this.bonus);
}
}
You can always get Atributes from other classes by writing Getters.
Also, as Pedro David already said you can't use "class" for naming classes and variables as it is a Reserved Word.
This being said, here is my solution for your problem (It's far from perfect but hopefully you'll see how to easily share information between classes)
import java.util.*;
public class CharacterCreationProgam {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
try {
System.out.println("Welcome to the super simple character creator ");
System.out.println("Choose class: 1: Warrior 2: Wizard 3: Rogue 4: Healer ");
int race = input.nextInt();
//creating new Player-Object:
Player player = new Player(race);
System.out.println("New character has been made: ");
//Character stats:
System.out.println("Print character stats? 1: Yes 2: No ");
int answer = input.nextInt();
if (answer == 1) {
System.out.println("Race: " + player.getRace().getraceName() +
"\nGender: " + player.getSex() +
"\nAge: " + player.getAge());
}
//Weapon stats:
System.out.println("Print weapon stats? 1: Yes 2: No ");
answer = input.nextInt();
if (answer == 1) {
Weapon playerWeapon = player.getWeapon();
System.out.println("Weapon Type: " + playerWeapon.getType() +
"\nDamage: " + playerWeapon.getDamage() +
"\nBonus: " + playerWeapon.getBonus());
}
} catch (Exception e) {
System.err.println("Error: " + e);
}finally{
input.close();
}
}
}
Here is my go at a Player.java:
public class Player {
private Race playerRace;
private String sex;
private int age;
private Weapon weapon;
public Player(int race) throws Exception{
setRace(race);
setAtributes();
setWeapon();
}
private void setRace(int race) throws Exception{
this.playerRace = new Race(race);
}
private void setAtributes() throws Exception{
switch (playerRace.getraceName()) {
case "Warrior":
this.sex = "Male";
this.age = 45;
break;
case "Wizard":
this.sex = "Female";
this.age = 30;
break;
case "Rogue":
this.sex = "Female";
this.age = 25;
break;
case "Healer":
this.sex = "Male";
this.age = 21;
break;
default:
throw new Exception();
}
}
private void setWeapon() throws Exception{
weapon = new Weapon(playerRace);
}
public String getSex(){
return sex;
}
public int getAge(){
return age;
}
public Weapon getWeapon(){
return weapon;
}
public Race getRace(){
return playerRace;
}
}
My Race.java:
public class Race {
private String raceName; //Enum would be BP
private int raceLevel;
private String specialSkill; //Another Class for the skills would be Nice in the long run
public Race(int race) throws Exception{
setRace(race);
}
private void setRace(int race) throws Exception{
switch (race) {
case 1: //Warrior
this.raceName = "Warrior";
this.raceLevel = 90;
this.specialSkill = "Damage reduction";
break;
case 2: //Wizard
this.raceName = "Wizard";
this.raceLevel = 75;
this.specialSkill = "Magic";
break;
case 3: //Rogue
this.raceName = "Rogue";
this.raceLevel = 55;
this.specialSkill= "Dodge";
break;
case 4: //Healer
this.raceName = "Healer";
this.raceLevel = 69;
this.specialSkill= "Healing";
break;
default:
throw new Exception(); //you should find a fitting Exception for this
}
}
public String getraceName(){
return this.raceName;
}
public int getraceLevel(){
return this.raceLevel;
}
public String specialSkill(){
return this.specialSkill;
}
}
And the Weapon.java:
public class Weapon {
private int damage;
private String type;
private String bonus;
public Weapon(Race race) throws Exception{
setWeapon(race);
}
private void setWeapon(Race race) throws Exception{
switch (race.getraceName()) {
case "Warrior":
this.type = "Sword";
this.damage = 75;
this.bonus = "Armor penetration";
break;
case "Wizard":
this.type = "Staff";
this.damage = 35;
this.bonus = "Spell casting";
break;
case "Rogue":
this.type = "Daggers";
this.damage = 55;
this.bonus = "Poisoning enemies";
break;
case "Healer":
this.type = "Hammer";
this.damage = 85;
this.bonus = "Stunning enemies";
break;
default:
throw new Exception();
}
}
public int getDamage(){
return damage;
}
public String getType(){
return type;
}
public String getBonus(){
return bonus;
}
}
So as you can see I use Switch statements with the getters from the objects. I hope this is somewhat helpful, if you have any questions please ask ;)

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.

Cannot find symbol in Java application

I am working on a simple text-based rpg battler program as an introduction to Java. I seem to have a decent understanding of the majority of code, but I have ran into a couple of issues.
The issues I am having are in the Project class.
In my switch statement I am trying to use the setSpells() and setArrows() methods and I am getting a "cannot find symbol" error message. I realize that this is probably due to something I have set up incorrectly in the sub-classes, but I am unsure what that is.
The second issue is in the print statement pulling the character name by use of c.getName(). The c part of that statement gives the same error message.
Is there something simple that I am misunderstanding in these situations? Any help resolving this would be appreciated. Thank you.
Here is my main project class file:
package project;
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
System.out.println("Welcome to Lands of the Sun\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Please choose your class (wizard or elf): \n");
String classChoice = sc.next();
sc.nextLine();
System.out.print("Please choose a name for your " + classChoice + ": ");
String charName = sc.next();
sc.nextLine();
int healthVal = (int) (Math.random() * 10) + 1;
switch (classChoice) {
case "wizard":
{
Character c = new Wizard();
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setSpells(10);
break;
}
case "elf":
{
Character c = new Elf();
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setArrows(10);
break;
}
}
System.out.print(c.getName());
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
Here is my Character class:
package project;
public abstract class Character {
private String name;
private int gold;
private int health;
public static int count = 0;
public Character()
{
name = "";
gold = 0;
health = 0;
}
public Character(String name, int gold, int health) {
this.name = name;
this.gold = gold;
this.health = health;
}
public void setName(String name)
{
this.name = name;
}
public String getName(){
return name;
}
public void setGold(int gold)
{
this.gold = gold;
}
public int getGold()
{
return gold;
}
public void setHealth(int health)
{
this.health = health;
}
public int getHealth()
{
return health;
}
#Override
public String toString()
{
return "Name: " + name + "\n" +
"Gold: " + gold + "\n" +
"Health: " + health + "\n";
}
public static int getCount()
{
return count;
}
public abstract String getDisplayText();
}
Here is my Wizard sub-class:
package project;
public class Wizard extends Character {
private int spells;
public Wizard()
{
super();
spells= 0;
count++;
}
public void setSpells(int spells)
{
this.spells= spells;
}
public int getSpells(){
return spells;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Spells: " + spells+ "\n";
}
}
And finally my Elf sub-class:
package project;
public class Elf extends Character{
private int arrows;
public Elf()
{
super();
arrows = 0;
count++;
}
public void setArrows(int arrows)
{
this.arrows = arrows;
}
public int getArrows(){
return arrows;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Arrows: " + arrows + "\n";
}
}
When you create one of your Characters...
Character c = new Elf();
You are downcasting the instance to "act" like Character, this is very useful feature in Object Oriented Programming, but is causing you issues in this case, as Character does not have the methods you are looking for.
Instead, start by assigning the class to a concrete version of the instance...
Elf elf = new Elf();
Apply the properties you need and then assign it to a Character reference...
Character c = null;
//...
switch (classChoice) {
//...
case "elf":
{
Elf elf = new Elf();
//...
c = elf;
}
}
c = elf;
for example...
Have a look at the section on Polymorphism for more details
Your issue is with these lines
Character c = new Wizard();
....
Character c = new Elf();
The character class itself doesn't have the setFireballs or SetArrows methods. You need to define the object as a wizard or elf in order to get access to said methods... EG:
Elf c = new Elf();
Wizard c = new Wizard();
etc
Character c = new Wizard();
Character has neither a setFireBalls method nor a setArrows method.
I have made the some changes to your code..
here is the final code.
package h;
import java.util.Scanner;
public class he {
public static void main(String[] args) {
System.out.println("Welcome to Lands of the Sun\n");
Character c = new Wizard();
Character e = new Elf();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Please choose your class (wizard or elf): \n");
String classChoice = sc.next();
sc.nextLine();
System.out.print("Please choose a name for your " + classChoice + ": ");
String charName = sc.next();
sc.nextLine();
int healthVal = (int) (Math.random() * 10) + 1;
switch (classChoice) {
case "wizard":
{
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setFireballs(10);
break;
}
case "elf":
{
;
e.setName(charName);
e.setGold(25);
e.setHealth(healthVal);
e.setArrows(10);
break;
}
}
System.out.print(c.getName());
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
Wizard class
public class Wizard extends Character {
private int fireballs;
public Wizard()
{
super();
fireballs = 0;
count++;
}
public void setFireballs(int fireballs)
{
this.fireballs = fireballs;
}
public int getFireballs(){
return fireballs;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Fireballs: " + fireballs + "\n";
}
#Override
public void setArrows(int i) {
}
}
Elf class
public class Elf extends Character {
private int arrows;
public Elf()
{
super();
arrows = 0;
count++;
}
public void setArrows(int arrows)
{
this.arrows = arrows;
}
public int getArrows(){
return arrows;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Arrows: " + arrows + "\n";
}
#Override
public void setFireballs(int i){
}
}
abstract class Character
public abstract class Character {
private String name;
private int gold;
private int health;
public static int count = 0;
public Character() {
name = "";
gold = 0;
health = 0;
}
public Character(String name, int gold, int health) {
this.name = name;
this.gold = gold;
this.health = health;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setGold(int gold) {
this.gold = gold;
}
public void setHealth(int health) {
this.health = health;
}
public int getHealth() {
return health;
}
#Override
public String toString() {
return "Name: " + name + "\n" + "Gold: " + gold + "\n" + "Health: "
+ health + "\n";
}
public static int getCount() {
return count;
}
public abstract String getDisplayText();
public abstract void setFireballs(int i);
public abstract void setArrows(int i);
}
hope this helps...

Categories