I am currently finishing a University practice exam in the run up to my exam in the summer. Below is the code which I have completed so far:
I am struggling with one of the parts of the assignment. What it asks me to do is: "In the tester02, create a method called startRobot, which will be a polymorphic method. This method will accept an object of type Robot and a Scanner object. The purpose of the method is to start the robot, get the robot to undertake a task method(you must run the two versions of the doTask method here) and then to stop the robot."
so basically it asks me to create the polymorphic method and call it twice, first time passing the EntertainmentRobot into it and then the second time HumanStudyRobot. I am not sure how to set this up in the tester as I am just receiving errors when trying to write the code. I'm not really familiar with polymorphic methods / polymorphism either.
Any help at all would be much appreciated!
package Program;
import java.util.Scanner;
public abstract class Robot {
//instance variables
protected double EnergyUnitsRequired;
protected double height;
protected String manufacturer;
protected String name;
protected String purpose;
protected double weight;
protected double energy;
//constructor
public Robot(String name, double height, double weight, String manufacturer) {
super();
this.EnergyUnitsRequired = 0.25;
this.height = height;
this.manufacturer = manufacturer;
this.name = name;
this.purpose = "The robot's purpose needs to be provided";
this.weight = weight;
this.energy = 0.0;
}
//accessors & mutators
public double getEnergyUnitsRequired() {
return EnergyUnitsRequired;
}
public double getHeight() {
return height;
}
public String getManufacturer() {
return manufacturer;
}
public String getName() {
return name;
}
public String getPurpose() {
return purpose;
}
public double getWeight() {
return weight;
}
public double getEnergy() {
return energy;
}
public void setEnergyUnitsRequired(double energyUnitsRequired) {
EnergyUnitsRequired = energyUnitsRequired;
}
public void setHeight(double height) {
this.height = height;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public void setName(String name) {
this.name = name;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public void setWeight(double weight) {
this.weight = weight;
}
//methods
public abstract void start();
public abstract void stop();
public abstract void doTask();
public abstract void doTask(Scanner input);
public void energyConsumption() {
System.out.println("The robot: " + getName() + " has: " + getEnergy() + " to begin with.");
double priorEnergy = getEnergy();
energy = energy - energyRequired(); //the variable energyRequired should be returned from the energyRequired method below this method.
System.out.println("My energy has depleted by the following amount: " + (priorEnergy - energy) + " units.");
System.out.println("My energy is now at: " + energy + " units.");
}
public double energyRequired() {
double energyRequired = (EnergyUnitsRequired * weight);
return energyRequired;
}
public void regenerate() {
energy = getEnergy() + (getWeight() * 2);
System.out.println("More energy is being generated for the robot.");
}
}
package Program;
import java.util.Scanner;
public class HumanStudyRobot extends Robot {
//instance variables
public HumanStudyRobot(String name, double height, double weight, String manufacturer) {
super(name, height, weight, manufacturer);
this.energy = 30.0;
}
#Override
public void start() {
System.out.println("This is a Human Study Robot");
System.out.println("The robot has started studying.");
}
#Override
public void stop() {
System.out.println("The robot has finished studying.");
}
#Override
public void doTask() {
study();
}
#Override
public void doTask(Scanner input) {
// TODO Auto-generated method stub
}
public void study() {
if (energy >= energyRequired()) {
energyConsumption();
}
else
if (energy < energyRequired()) {
System.out.println("The robot does not have sufficient energy.");
regenerate();
System.out.println("................");
System.out.println("The robot has finished regenerating");
}
}
public String toString() {
return "I AM A HUMAN STUDY ROBOT : \nThe details of the entertainment robot are below:\n"
+ "Name : " + getName() + "\nWeight: " + getWeight() + "\nHeight: "
+ getHeight() + "\nManufacturer : " + getManufacturer() + "\nPurpose : "
+ getPurpose();
}
}
package Program;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class EntertainmentRobot extends Robot {
//constructor
public EntertainmentRobot(String name, double height, double weight, String manufacturer) {
super(name, height, weight, manufacturer);
this.energy = 10.0;
this.EnergyUnitsRequired = 0.75;
}
#Override
public void start() {
System.out.println("This is an Entertainment Robot. \n The robot has started entertaining.");
}
#Override
public void stop() {
System.out.println("The Entertainment RObot has finsihed entertaining");
}
#Override
public void doTask() {
}
#Override
public void doTask(Scanner input) {
play();
}
public void talk() {
}
public void play () {
System.out.println("How many times would you like to play?");
if (getEnergy() >= energyRequired() ) {
energyConsumption();
}
else
if (getEnergy() < energyRequired()) {
System.out.println("The robot does not have sufficient energy to play.");
regenerate();
System.out.println("The robot is regenerating");
System.out.println(".........................");
System.out.println("The robot has finished regenerating!");
}
}
public String toString() {
return "\nI AM AN ENTERTAINMENT ROBOT \nThe details of the entertainment robot are below: \n" +
"Name : " + getName() + "\nHeight: " + getHeight() + "\nWeight: " + getWeight() + "\nManufacturer: " +
getManufacturer() + "\nPurpose: " + getPurpose();
}
}
package Program;
import java.util.Scanner;
public class Tester02 {
public static void main(String[] args) {
HumanStudyRobot HumanStudyRobot1 = new HumanStudyRobot("HRP", 1.5, 58.0, "Kawada Industries");
HumanStudyRobot1.setPurpose("Study into human movement and perform a wide range of tasks.");
/*
System.out.println(HumanStudyRobot1.toString());
HumanStudyRobot1.start();
HumanStudyRobot1.study();
HumanStudyRobot1.stop();*/
public void startRobot(Robot, Scanner input){
}
EntertainmentRobot EntertainmentRobot1 = new EntertainmentRobot("QRIO", 0.6, 7.3, "SONY");
EntertainmentRobot1.setPurpose("To live with you, make life fun and make you happy.");
System.out.println(HumanStudyRobot1.toString());
System.out.println(EntertainmentRobot1.toString());
}
}
First observation: your startRobot method signature is invalid, change it to
public void startRobot(Robot robot, Scanner input){
}
Second observation: move the method declaration outside of the main method.
Third observation: call startRobot from the main method with your robot and scanner parameters.
startRobot(EntertainmentRobot1, /*your scanner*/);
startRobot(HumanStudyRobot1, /*your scanner*/);
Since both classes extend the Robot class - they can be passed to the startRobot method. For further reading on this topic, consult the Oracle Documentation.
There's nothing wrong with the code here. Since you don't understand polymorphism principles I think you need to work on that; 3 robot classes
extend Robot class which is an abstract class, subclasses must override
super classes abstract methods. In your case the abstract methods are
public abstract void start();
public abstract void stop();
public abstract void doTask();
public abstract void doTask(Scanner input);
Since all robot classes are subclasses you can do something
like this
Robot humanrobot = new HumanStudyRobot("parameters...");
Robot entertainment = new EntertainmentRobot("parameters");
public void startRobot(Robot robot, Scanner input){
robot.dotask();
}
startRobot(humanrobot, scanner);
startRobot(entertainment, scanner);
im almost certain im on the same course as you, as im doing the exact same question, anyway after looking at what the people above have said, I got this working by doing this:
public static void main(String[] args) {
EntertainmentRobot jim = new EntertainmentRobot(0.6, "SONY", "QRIO", "To live with you, make life fun and make you happy", 7.3);
HumanStudyRobot jeff = new HumanStudyRobot(1.5, "Kawada Industries", "HRP", "Study into human movement and perfrom a wide range of tasks", 58.0);
//System.out.println(jim);
//System.out.println(jeff);
//EntertainmentRobot jim = robot();
Scanner input = new Scanner(System.in);
startRobot(jim, input);
startRobot(jeff, input);
}
public static void startRobot(Robot robot, Scanner input) {
/*
* POLYMORPHIC METHOD
* Accept an object of type robot
* Scanner object
* Start the robot
* Get robot to undertake a task
* stop the robot
*/
robot.start();
robot.doTask();
robot.stop();`enter code here`
}
}
Related
I have a simple pizza program in Java, made using the Factory Pattern.
Basically, when a factory is given as a parameter, it creates a particular pizza, which is then added to the list of pizzas of the PizzaShop.
I would like to create a method that displays how many particular pizzas I have. For instance, when the method is called, I would like it to display something like "We have 5 PizzaChicago and 3 PizzaNewYork". I am not sure how to do that.
This is my code.
public interface Pizza {
String name();
}
public class PizzaChicago implements Pizza{
public Integer price;
public PizzaChicago(Integer price){
this.price = price;
}
#Override
public String name() {
return this.getClass().getSimpleName();
}
}
public class PizzaNewYork implements Pizza{
public Integer price;
public PizzaNewYork(Integer price){
this.price = price;
}
#Override
public String name() {
return this.getClass().getSimpleName();
}
}
public interface PizzaFactory {
public Pizza createPizza(Integer price);
}
public class PizzaNewYorkFactory implements PizzaFactory{
#Override
public Pizza createPizza(Integer price) {
return new PizzaNewYork(6);
}
}
public class PizzaChicagoFactory implements PizzaFactory{
#Override
public Pizza createPizza(Integer price) {
return new PizzaChicago(8);
}
}
import java.util.ArrayList;
import java.util.List;
public class PizzaShop {
List<Pizza> pizzaList = new ArrayList<>();
public void createPizza(PizzaFactory factory, Integer price){
Pizza pizza = factory.createPizza(price);
System.out.println(pizza.name() + " " + "was created");
pizzaList.add(pizza);
}
}
`
What you have to do is iterate the list and check what is the type of every object.
int countPizzaNewYork = 0, countPizzaChicago = 0;
for(Pizza p: pizzaList){
if(p instanceOf PizzaNewYork)
{
countPizzaNewYork++;
}
else
{
countPizzaChicago++;
}
}
System.out.println("We have "+ countPizzaChicago+" PizzaChicago and "+countPizzaNewYork+" PizzaNewYork");
Alternate approach (use Map instead of a List):
public class PizzaShop {
Map<String, Integer> pizzaDiary = new HashMap<>();
public void createPizza(PizzaFactory factory, Integer price) {
Pizza pizza = factory.createPizza(price);
System.out.println(pizza.name() + " " + "was created");
int previousCount = pizzaDiary.getOrDefault(pizza.name(), 0);
pizzaDiary.put(pizza.name(), previousCount + 1);
}
}
Use the pizzaDiary map to print out your pizza counts.
Having a separate class for each pizza could be problematic and somewhat cumbersome. And for certain using the class name and instanceof is not the way to go. Have you considered using an Enum to represent the Pizzas? Here is an example of how it might work.
public class PizzaShopDemo {
enum Pizza {
CHICAGOPIZZA(8, "Chicago Pizza"),
NEWYORKPIZZA(6, "New York Pizza");
private double price;
private String name;
private int count = 0;
private Pizza(double price, String name) {
this.price = price;
this.name = name;
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
public void update() {
count++;
}
public int getCount() {
return count;
}
}
public static void main(String[] args) {
new PizzaShopDemo().pizzaShop();
}
public void pizzaShop() {
createPizza(Pizza.CHICAGOPIZZA);
createPizza(Pizza.NEWYORKPIZZA);
createPizza(Pizza.CHICAGOPIZZA);
createPizza(Pizza.NEWYORKPIZZA);
createPizza(Pizza.CHICAGOPIZZA);
createPizza(Pizza.CHICAGOPIZZA);
createPizza(Pizza.NEWYORKPIZZA);
for (Pizza p : Pizza.values()) {
System.out.println(p.getName() + ", " + p.getPrice()
+ ", " + p.getCount());
}
}
public void createPizza(Pizza type) {
type.update();
// other stuff here.
}
}
Prints
Chicago Pizza, 8.0, 4
New York Pizza, 6.0, 3
So, I'm still learning java and coding so the resolution may be obvious but I just can't see it.
I'm writing a code about stars and constelations for uni assignment.
package com.company;
import java.util.*;
public class Main {
static public class Constellation {
public List<Star> constellation;
public String nameOfConstellation;
public Constellation(List<Star> constellation, String nameOfConstellation) {
this.constellation = constellation;
this.nameOfConstellation = nameOfConstellation;
}
public List<Star> getConstellation() {
return constellation;
}
}
static public class Star {
// private String categoryName;
private Constellation constellation;
private String nameOfConstelation;
public String getCategoryName() {
int index = constellation.getConstellation().indexOf(this);
String categoryName;
return categoryName = GreekLetter.values[index] + " " + this.constellation.nameOfConstellation;
}
public void deleteStar(Star x) {
this.constellation.constellation.remove(x);
}
}
public enum GreekLetter {
alfa,
beta,
gamma,
delta,
epsilon,
dzeta,
eta;
static public final GreekLetter[] values = values();
}
public static void main(String[] args)
{
Star x = new Star();
List<Star> fishCon = new ArrayList<>();
Constellation Fish = new Constellation(fishCon, "Fish");
x.constellation=Fish;
fishCon.add(x);
x.getCategoryName();
Star y = new Star();
y.constellation=Fish;
fishCon.add(y);
y.getCategoryName();
x.deleteStar(x);
for (Star w : Fish.constellation)
{
System.out.println(w.getCategoryName());
}
}
}
My point is to Update field categoryName after deleting one star. categoryName value is set in order of adding another star. For example I have first star - the name will be Alfa + nameOfConstelation. Second star - Beta + nameOfConstelation. When I call method deleteStar() I want to update all categoyName of my stars in constelation. Calling methods in deleteStar() doesn't work probably due to add() in setCategoryName. I would really appreciate any hints!
Since this appears to be homework, I am not posting code in this answer but rather giving suggestions that can help you create your own workable code:
Create a class called Constellation that holds the Stars in an List<Star> starList = new ArrayList<>();
Give Constellation a public List<Star> getStarList() method
Give each Star a Constellation field to hold the Constellation that contains this Star
Give each Star a getCategoryName() method that gets the Constellation object, iterates through its starList using a for-loop until it finds the this Star, and then that returns the appropriate name based on the index of the Star in the list.
Thus, if a Star is removed from the starList, the category names of all the other Stars held by that Constellation will update automatically and dynamically
Also,
You can give Constellation a public void deleteStar(Star star) method where it removes the Star parameter from its starList
You can also give Star a public void deleteFromConstellation() method where it checks its Constellation field, constellation, and if not null, calls constellation.deleteStar(this); and then sets the constellation field to null
Get rid of the private String categoryName; field in Star. This should be a calculated field, meaning the public String getCategoryName() does not return a field, but a String based on code (as described above).
It first checks that Star's constellation field is not null
It then gets the index of the Star in the Constellation's starList (I have given my Constellation class a public int getIndexOfStar(Star star) method.
It then uses this, the GreekLetter class, and the constellation.getName() method to create a String to return
Done.
Since you've figured this out, this is another way to code it:
public class SkyMain {
public static void main(String[] args) {
Constellation fish = new Constellation("Fish");
Star x = new Star();
Star y = new Star();
fish.addStar(x);
fish.addStar(y);
System.out.println("before removing x");
System.out.println("x category name: " + x.getCategoryName());
System.out.println("y category name: " + y.getCategoryName());
System.out.println("fish constellation: " + fish);
fish.removeStar(x);
System.out.println();
System.out.println("after removing x");
System.out.println("x category name: " + x.getCategoryName());
System.out.println("y category name: " + y.getCategoryName());
System.out.println("fish constellation: " + fish);
}
}
public class Star {
private Constellation constellation;
public void setConstellation(Constellation constellation) {
this.constellation = constellation;
}
public void removeFromConstellation() {
if (constellation != null) {
constellation.removeStar(this);
}
}
public String getCategoryName() {
if (constellation != null) {
int index = constellation.getIndexOfStar(this);
return GreekLetter.getGreekLetter(index).getName() + " " + constellation.getName();
} else {
return "";
}
}
#Override
public String toString() {
return getCategoryName();
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Constellation implements Iterable<Star> {
private String name;
private List<Star> starList = new ArrayList<>();
public Constellation(String name) {
this.name = name;
}
public String getName() {
return name;
}
public List<Star> getStarList() {
return starList;
}
public void addStar(Star star) {
starList.add(star);
star.setConstellation(this);
}
public void removeStar(Star star) {
if (starList.contains(star)) {
starList.remove(star);
star.setConstellation(null);
}
}
public int getIndexOfStar(Star star) {
return starList.indexOf(star);
}
#Override
public Iterator<Star> iterator() {
return starList.iterator();
}
#Override
public String toString() {
return "Constellation [name=" + name + ", starList=" + starList + "]";
}
}
public enum GreekLetter
{
ALPHA("alpha", 0),
BETA("beta", 1),
GAMMA("gamma", 2),
DELTA("delta", 3),
EPSILON("epsilon", 4),
ZETA("zeta", 5),
ETA("eta", 6);
private String name;
private int index;
private GreekLetter(String name, int index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public int getIndex() {
return index;
}
public static GreekLetter getGreekLetter(int index) {
if (index < 0 || index > values().length) {
throw new IllegalArgumentException("for index " + index);
} else {
return values()[index];
}
}
}
I am struggling with an inheritance task in Java
I was given an Animal.java class. My homework is to create a subclass called Lion.java. One of the tasks I'm struggling with within the entire task is outputting the type of Lion it is based on the weight of the lion. This is the code for the Animal.java
public class Animal {
private int numTeeth = 0;
private boolean spots = false;
private int weight = 0;
public Animal(int numTeeth, boolean spots, int weight){
this.setNumTeeth(numTeeth);
this.setSpots(spots);
this.setWeight(weight);
}
public int getNumTeeth(){
return numTeeth;
}
public void setNumTeeth(int numTeeth) {
this.numTeeth = numTeeth;
}
public boolean getSpots() {
return spots;
}
public void setSpots(boolean spots) {
this.spots = spots;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public static void main(String[] args){
Lion lion = new Lion(30, false, 80);
System.out.println(lion);
}
}
This is my code for the Lion.java class so far:
public class Lion extends Animal {
String type = "";
public Lion(int numTeeth, boolean spots, int weight) {
super(numTeeth, spots, weight);
}
public String type(int weight){
super.setWeight(weight);
if(weight <= 80){
type = "Cub";
}
else if(weight <= 120){
type = "Female";
}
else{
type = "Male";
}
return type;
}
#Override
public String toString() {
String output = "Number of Teeth: " + getNumTeeth();
output += "\nDoes it have spots?: " + getSpots();
output += "\nHow much does it weigh: " + getWeight();
output += "\nType of Lion: " + type;
return output;
The problem is the output does not return the type based on the if statement above. It's probably a very simple solution but I can't seem to figure it out.
In toString method, instead of type replace with type() method.
#Override
public String toString() {
String output = "Number of Teeth: " + getNumTeeth();
output += "\nDoes it have spots?: " + getSpots();
output += "\nHow much does it weigh: " + getWeight();
output += "\nType of Lion: " + type(getWeight());
return output;
Take a good look at your Lion constructor
public Lion(int numTeeth, boolean spots, int weight) {
super(numTeeth, spots, weight);
}
This doesn't do anything for the type (your public type method).
In order to set the private type class variable you need to either call the type method in the constructor or after the object has been created but before you call the toString method. For example
public Lion(int numTeeth, boolean spots, int weight) {
super(numTeeth, spots, weight);
type(weight);
}
Note that, as pointed out in the comments, you probably would be better off handling the type directly in the setWeight method. You can do something like
#Override
public void setWeight(int weight) {
super.setWeight(weight);
type(weight);
}
and leave the constructor alone.
Taking it one step further, you could refactor your code such that the type method has no parameter (you've already set the weight member).
I was told that i should make a JUnit Test to check if all the codes are working. I dont know anything about JUnit that Is why im asking you guys. Anyway, here is my code:
package cst8284.shape;
public abstract class BasicShape {
private double width;
public double getWidth(){return width;}
public void setWidth(double width){this.width = width;}
#Override
public String toString(){
return ("BasicShape Overrides " + super.toString());
}
public abstract double getArea();
public abstract double getPerimeter();
}
Here is where i should make testing,
package cst8284.shape;
public class TestBasicShape {
public static void main(String[] args){
Circle circle = new Circle(2.0);
System.out.println(circle.toString());
System.out.println("The perimeter of the circle is " + circle.getPerimeter());
System.out.println("The area of the circle is: " + circle.getArea() + "\n");
Square square = new Square(2.0);
System.out.println(square.toString());
System.out.println("The perimeter of the square is " + square.getPerimeter());
System.out.println("The area of the square is: " + square.getArea() + "\n");
Rectangle rect1 = new Rectangle(2.0,3);
System.out.println(rect1.toString());
System.out.println("The perimeter of the rectangle is " + rect1.getPerimeter());
System.out.println("The area of the rectangle is: " + rect1.getArea() +"\n");
Rectangle rect2 = new Rectangle(rect1);
Rectangle rect3 = new Rectangle(2.0, 1.0);
System.out.println("The square and the circle are " + (square.equals(circle)?"":"not ") + "equal");
System.out.println("The rectangle and the square are " + (rect1.equals(square)?"":"not ") + "equal");
System.out.println("Rectangles 1 and 2 are " + (rect2.equals(rect1)?"":"not ") + "equal");
System.out.println("Rectangles 2 and 3 are " + (rect2.equals(rect3)?"":"not ") + "equal");
}
}
package cst8284.shape;
public class Circle extends BasicShape {
public Circle(){
}
public Circle(double width){
setWidth(width);
}
public Circle(Circle circle) {
setWidth(circle.getWidth());
}
//Getters
public double getArea() {
return Math.PI * (getWidth()/2) * (getWidth()/2);
}
public double getPerimeter() {
return 2*Math.PI*getWidth()/2;
}
#Override
public String toString(){
return ("Circle Overrides " + super.toString());
}
#Override
public boolean equals(Object obj){
if (!(obj instanceof Circle)) {
return false;
}
Circle c = (Circle)obj;
return (this.getWidth() == c.getWidth());
}
}
package cst8284.shape;
public class Square extends BasicShape{
public Square() {
}
public Square(double width) {
setWidth(width);
}
public Square(Square square) {
setWidth(square.getWidth());
}
//Getters
public double getArea() {
return getWidth()*2;
}
public double getPerimeter() {
return 4*getWidth();
}
#Override
public String toString(){
return ("Square Overrides " + super.toString());
}
#Override
public boolean equals(Object obj){
if (!(obj instanceof Square)) {
return false;
}
Square s = (Square)obj;
return (this.getWidth() == s.getWidth());
}
}
package cst8284.shape;
public class Rectangle extends Square{
private double height;
public Rectangle() {
}
public Rectangle(double width, double height) {
setWidth(width);
setHeight(height);
}
public Rectangle(Rectangle rectangle) {
setWidth(rectangle.getWidth());
setHeight(rectangle.getHeight());
}
public double getHeight(){
return height;
}
public void setHeight(double height){
this.height=height;
}
public double getArea() {
return getWidth()*getHeight();
}
public double getPerimeter() {
return 2*(getHeight()+getWidth());
}
#Override
public String toString(){
return ("Rectangle Overrides " + super.toString());
}
#Override
public boolean equals(Object obj){
if (!(obj instanceof Rectangle)) {
return false;
}
Rectangle r = (Rectangle)obj;
return (this.getWidth() == r.getWidth() && this.getHeight() == r.getHeight());
}
}
In this program, i am trying to calculate the area and perimeter of Circle and Square(subclasses of BasicShape) and Rectangle(subclass of Square) and also trying to compare whether each shape are equal(in shape or in size)
Thank you in advance!
I have found the easiest way to approach testing is to make a test class for each of the classes whose behaviour you would like to test in your system, and place these test classes in a separate package.
Then, say you want to test the methods in the rectangle class.
//imports
public void testRectangle(){
Rectangle rectange;
#Before
public void setup(){
rectangle = new Rectangle();
}
//Say you want to test whether the setHeight method works as it should
#Test
public void testSetHeight(){
rectangle.setHeight(10.0);
assertEquals(10.0, rectangle.getHeight());
}
//The rest of the methods you would like to test
A few things to note :
Methods in the test class never takes in any parameters.
#Before means the method is going to run before each of the test methods. This allows you to setup anything you will need for the tests to run. You must have #Test before each test method. The example I have provided above is very simple and by no means exhaustive, so you should look up the JUnit documentation and learn more.
Im trying to create a small character builder, using inheritance. i have CreateCharacter CharacterRace then a Dwarf class. i made a variable with type CharacterRace in CreateCharacter and a variable with type Dwarf in CharacterRace. i have an object of CreateCharacter in my main method demo and its not letting me call the methods from the Dwarf class, to make a dwarf character. im thinking ineed to pass a dwarf object in characterRace? im just not sure how. heres my code: (its a bit long my apologies)
package characterCreation;
public class CreateCharacter {
private CharacterClass characterClass;
private CharacterRace characterRace;
private Name name;
public CreateCharacter(String characterName,CharacterClass characterClass,CharacterRace characterRace) {
this.name = new Name(characterName);
this.characterClass = characterClass;
this.characterRace = characterRace;
}
public CreateCharacter(){
}
public CharacterClass getCharacterClass() {
return characterClass;
}
public void setCharacterClass(CharacterClass characterClass) {
this.characterClass = characterClass;
}
public CharacterRace getCharacterRace() {
return characterRace;
}
public void setCharacterRace(CharacterRace characterRace) {
this.characterRace = characterRace;
}
public Name getName(){
return name;
}
public void setName(Name name){
this.name = name;
}
#Override
public String toString() {
return "CreateCharacter [name=" + name + ", characterRace=" + characterRace + ", characterClass="
+ characterClass + "]";
}
}
package characterCreation;
public class CharacterRace {
protected String raceName;
protected double mana;
protected double hp;
private Dwarf dwarf;
public CharacterRace(String raceName,double mana, double hp) {
this.raceName = raceName;
this.mana = mana;
this.hp = hp;
}
public CharacterRace(){
}
public String getRaceName() {
return raceName;
}
public Dwarf getDwarf() {
return dwarf;
}
public void setDwarf(Dwarf dwarf) {
this.dwarf = dwarf;
}
public double getMana() {
return mana;
}
public double getHp() {
return hp;
}
#Override
public String toString() {
return "CharacterRace [dwarf=" + dwarf + "]";
}
}
package characterCreation;
public class Dwarf extends CharacterRace {
public Dwarf(String raceName,double mana, double hp) {
super(raceName,mana,hp);
}
public double getMana() {
mana = 5;
return mana;
}
public double getHp() {
hp = 10;
return hp;
}
public String getRaceName(){
return raceName = "Dwarf";
}
#Override
public String toString() {
return "Dwarf [mana=" + mana + ", hp=" + hp + ", getRaceName()=" + getRaceName() + "]";
}
}
package characterCreation;
import java.util.Scanner;
public class CharacterDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CreateCharacter create = new CreateCharacter();
System.out.println("Choose your Race: ");
String userRace = input.next();
create.setName(new Name("Daxel"));
//create.setCharacterRace(race);
System.out.println(create.getName());
//Dwarf dwarf = new Dwarf();
System.out.println(create.getCharacterRace().getDwarf().getRaceName());
//System.out.println(create.getCharacterRace().setDwarf(new Dwarf("dwarf",10,5)));
}
}
You have to call setCharacterRace() on create; then call setDwarf() on the characterRace; otherwise create.getCharacterRace() would be null and create.getCharacterRace().getDwarf() would throw NullPointerException.
I don't understand the logic behind your code, but try the code below:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CreateCharacter create = new CreateCharacter();
System.out.println("Choose your Race: ");
String userRace = input.next();
create.setName(new Name("Daxel"));
//***********new code starts******
CharacterRace myRace = new CharacterRace(userRace, 20, 9);
myRace.setDwarf(new Dwarf("dwarf",10,5));
create.setCharacterRace(myRace);
//***********new code ends********
//create.setCharacterRace(race);
System.out.println(create.getName());
//Dwarf dwarf = new Dwarf();
System.out.println(create.getCharacterRace().getDwarf().getRaceName());
//System.out.println(create.getCharacterRace().setDwarf(new Dwarf("dwarf",10,5)));
}