I don't get what's going on here, but the final method
s.castable()
that overrides the motherclass's namesake abstract method doesn't get called.
Here is where I try to call s.castable():
public void cast(String[] request) {
System.out.println("cast called");
if (this.session.getPlayer()==this.game.getTurnPlayer()) {
System.out.println("first condition passed");
Spell s = this.session.getPlayer().getCharacter().getSpells().get(Integer.valueOf(request[1]));
ArrayList<String> usernames = new ArrayList();
System.out.println("Now printing spell: "+s);
for (int i = 6; i < request.length; i++) {
usernames.add(request[i]);
}
System.out.println("username create.d");
if (s.castable()) { //HERE
System.out.println("Second condition passed");
s.cast(Integer.valueOf(request[1]), Integer.valueOf(request[2]),request[3].charAt(0), request[4].charAt(0), usernames);
String str = "";
for (String st : usernames) {
str += st;
}
this.session.send("YOUSPELL "+request[1]+" "+request[2]+" "+request[3]+" "+request[4]+" "+str);
System.out.println("Done");
}
}
}
Here is the "Spell" MotherClass:
public abstract class Spell {
private int manaCost;
private int coolDown;
private int range;
private Player player;
public abstract void cast(int x, int y, char mode1, char mode2,ArrayList<String> usernames);
public abstract Boolean castable();
//Then all getters and setters.
}
And here is the final class "Velocity":
public final class Velocity extends Spell {
private final int manaCost;
private final Player player;
private final int coolDown;
private final int coolDownTime;
private final int additionalMovement;
private final int spellRef;
private final ArrayList<String> usernames = new ArrayList();
public Velocity(Player p) {
this.spellRef = 0;
this.additionalMovement = 5;
this.player = p;
this.manaCost = 5;
this.coolDownTime = 3;
this.coolDown = 0;
super.setCoolDown(coolDown);
super.setManaCost(manaCost);
super.setPlayer(p);
}
#Override
public final void cast(int x, int y, char mode1, char mode2,ArrayList<String> usernames) {
System.out.println("Velocity casted.");
player.setMovement(player.getMovement() + additionalMovement);
setCoolDown(coolDownTime);
}
#Override
public final Boolean castable() {
System.out.println(player.getMana());
System.out.println(manaCost);
System.out.println(getCoolDown());
if (player.getMana() >= manaCost && getCoolDown() >= 0) {
return true;
}
return false;
}
}
Finally, the console output:
cast called
first condition passed
Now printing spell: model.haraka.be.Velocity#739bb60f
username create.d.
As you can see the spell object is known.
Can you help me ?
Thank you
The only possible problem here can be that Abstract class Spell's variable s doesn't contain the reference to Velocity object.
hence the castable method of velocity class never gets called.
If the castable method is returning false as mentioned by many
people System.out.println() statements must be printed which is not
the case I think.
But to be sure this is the problem, Please explain:
Spell s = this.session.getPlayer().getCharacter().getSpells().get(Integer.valueOf(request[1]));
What are below methods return type ?
getPlayer()
getSpells()
get(Integer.valueOf(request[1])
This is too much to ask/comment in comment section hence posting as an answer.
Related
I am creating a boardgame in java, and I'm trying to write a method that flags a chosen object (object represents a Tile on the board) by the user during the game. The method is within a class that sets a single Tile's value and position on the board.
I think using enum types would be a good idea but I am not sure exactly how to implement this. Within my class I have methods that get a Tile's position(row, column) on the grid, and the letter of which it represents.
public class Tile {
private final String letter; //holds the letter value of the tile
private final int row; //holds tile row index
private final int column;
public Tile(String l, int r, int c) {
this.letter = l;
this.row = r;
this.column = c;
}
//setter&getter methods
public String toString() {
return this.getLetter()+" "+ this.getRow() +
"," + this.getColumn();
}
So within this class as well, I want to write a method that flags whether or not a tile object is chosen... I was thinking that if the toString method returns a statement, then that can be used to show that the tile has been chosen. Or... how should I go about this. This is what I have so far:
public enum Status {CHOSEN, NOTCHOSEN};
public static void tileStatus(Status stat){
switch(stat) {
case CHOSEN: //something
break;
case NOTCHOSEN: //something
break;
}
}
you can declare that enum is instance member of Tile class
public class Tile {
private final String letter; //holds the letter value of the tile
private final int row; //holds tile row index
private final int column;
private Status flag; // use getter and setter to set flag on using Status enum
public Tile(String l, int r, int c) {
this.letter = l;
this.row = r;
this.column = c;
}
//setter&getter methods
public String toString() {
return this.getLetter()+" "+ this.getRow() +
"," + this.getColumn();
}
Adding a boolean to the Tile may help you with the state. Since there are only two possible states (chosen, not chosen), a boolean may make more sense. Also don't add getters and setters by default. Only when you need them. Refer to "tell don't ask principle"
public class Tile {
private final String letter; //holds the letter value of the tile
private final int row; //holds tile row index
private final int column;
private boolean isTileFlagged;
public Tile(String l, int r, int c) {
this.letter = l;
this.row = r;
this.column = c;
isTileFlagged = false; // May be false to being with
}
// add getters/setters only when necessary
public void toggleFlaggedState(){
isTileFlagged = !isTileFlagged;
}
public String toString() {
return this.getLetter()+" "+ this.getRow() +
"," + this.getColumn();
}
// add hashcode, equals if necessary
Also, if the enum is necessary, it could be an inner state of Tile class, as its independent existence may not make sense.
Make enum as member variable of class and method to the enum.
like this as bellow:-
package com.robo.lab;
public class Tile {
private final String letter; // holds the letter value of the tile
private final int row; // holds tile row index
private final int column;
private Status status;
public Tile(String l, int r, int c,Status status) {
this.letter = l;
this.row = r;
this.column = c;
this.status=status;
}
// setter&getter methods
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String toString() {
return this.getLetter() + " " + this.getRow() + "," + this.getColumn()+","+this.getStatus();
}
public String getLetter() {
return letter;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}
package com.robo.lab;
public enum Status {
CHOSEN, NOTCHOSEN;
public static void tileStatus(Status stat) {
switch (stat) {
case CHOSEN: // something
break;
case NOTCHOSEN: // something
break;
}
}
}
package com.robo.lab;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Tile obj1= new Tile("AUser", 1, 1,Status.CHOSEN);
System.out.println(obj1.toString());
Tile obj2= new Tile("BUser", 1, 1,Status.NOTCHOSEN);
System.out.println(obj2.toString());
}
}
My problem is that, simply I don't know what code to use to get my value from my getX method to my other classses main method.
package hangman;
public class Hangman {
private int triesLimit;
private String word;
public void setTriesLimit(int triesLimit) {
this.triesLimit = triesLimit;
}
public void setWord(String word) {
this.word = word;
}
public int getTriesLimit() {
return this.triesLimit;
}
public String getWord() {
return this.word;
}
#Override
public String toString() {
return ("Enter Secret Word " + this.getWord()
+ ".\nEnter max # of tries (Must be under 7) "
+ this.getTriesLimit());
}
}
Thats from the sub-class and I am trying to store the value of the triesLimit into the main of this classes main method
package hangman;
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
Scanner scn = new Scanner(System.in);
int triesCount = 0;
int correctCount = 0;
hangman.toString();
int triesLimit = hangman.getTriesLimit();
String secretWord = hangman.getWord();
StringBuilder b = new StringBuilder(secretWord.length());
for (int i = 0; i < secretWord.length(); i++) {
b.append("*");
}
char[] secrectStrCharArr = secretWord.toCharArray();
int charCnt = secretWord.length();
for (int x = 0; triesCount < triesLimit; triesCount++) {
while (charCnt >= 0) {
System.out.println("Secrect Word :" + b.toString());
System.out.println("Guess a letter :");
char guessChar = scn.next().toCharArray()[0];
for (int i = 0; i < secrectStrCharArr.length; i++) {
if (guessChar == secrectStrCharArr[i]) {
b.setCharAt(i, guessChar);
correctCount++;
} else if (guessChar != secrectStrCharArr[i]) {
triesCount++;
System.out.println("Incorrect: " + triesCount);hangmanImage(triesCount,correctCount);
}
}
}
}
}
I tried looking it up on here but couldn't find setters and getters used in a sub/superclass
You need to create an instance of the class in the main method to access the variables and method available in that class like so
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
hangman.setTriesLimit(2)
int value = hangman.getTriesLimit();
}
You can look into static keyword to access the value directly but that requires a bit more understanding of OOP's and JAVA.
This should work fine.
Hope it helps :)
EDITED
ToString method is just to convert everything in your model class to String which you have done correctly,but you have implemented incorrectly.... Change your ToString content so
#Override
public String toString() {
return ("The Secret Word you entered: " + this.getWord()
+ ".\n The max # of tries (Must be under 7): "
+ this.getTriesLimit());
}
You have initialized Scanner which does what you want, to ask the user to enter the values but again you haven't implemented it so add this to your main method
Scanner scn = new Scanner(System.in);
hangman.setTriesLimit(scn.nextInt());
hangman.setWord(scn.next());
hangman.toString()//Will work now
Trial and error is your best friend now :)
and Google some of the issues rather than waiting for an answer :)
Like rohit said, this is as simple as understand the basics of OOP, specific the encapsulation.
If you want to get a little deeper into OOP patterns, you could use the Observer pattern. This allows you to change the status of any class instance, even if they're not related by inheritance, aggregation, etc.
You can scale the solution by making List of Observer
Your observable interface
public interface IObservable {
// Set the observer
public void setObserver(IObserver iObserver);
// Notify the observer the current status
public void notifyObserver();
}
Your observer interface
public interface IObserver {
public void update(boolean status);
}
Your observer implementation
public class PlayHangman implements IObserver {
private boolean status = false;
public void printStatus() {
System.out.println("Status: " + (this.status ? "Win" : "Lose"));
}
#Override
public void update(boolean status) {
// The instance status is updated
this.status = status;
// Print the current status
this.printStatus();
}
}
Your observable implementation
public class Hangman implements IObservable{
private String goalWord = "";
private String currentWord = "";
private int triesLimit = 0;
private int tries = 0;
private IObserver iObserver;
public Hangman(String goalWord, int triesLimit) {
this.goalWord = goalWord;
this.triesLimit = triesLimit;
}
public void setCurrentWord(String currentWord) {
this.currentWord = currentWord;
this.notifyObserver();
}
public void addTry() {
this.tries++;
this.notifyObserver();
}
#Override
public void setObserver(IObserver iObserver) {
this.iObserver = iObserver;
}
#Override
public void notifyObserver() {
// True = win
this.iObserver.update(this.tries < this.triesLimit &&
this.goalWord.equals(this.currentWord));
}
}
Your Main class
public class Main{
public static void main(String[] args) {
// PlayHangman (game status)
PlayHangman playHangman = new PlayHangman();
// Hangman initializes with a goalWord and the triesLimit
Hangman hangman = new Hangman("HangmanJava", 5);
// Set the observer
hangman.setObserver(playHangman);
// During the game you just can set the current word and add a try
// You're not setting the status directly, that's the magic of the Observer pattern
hangman.setCurrentWord("Hang");
hangman.addTry();
hangman.setCurrentWord("HangmanJava");
}
}
Hope this helps and enjoy Java
I am working on a java project which contains 3 classes and an object array in one of the classes. This project is ultimately supposed to move 4 entity objects around on a board by using the coordinates of the entity objects. These entity objects are stored in an array in the world class. My problem is with the array initialization in the world class. I am not sure how to set each element of the array equal to an object from the entity class and then access that object's coordinates to move it around on the board. The coordinates for the entity objects are initially set at 20x30 in a default constructor. Here is my code:
public class entity {
private int xcoordinate;
private int ycoordinate;
private String name;
private char symbol;
public entity(){
xcoordinate = 20;
ycoordinate = 30;
}
private entity(int newxcoor, int newycoor, String newname, char newsymbol){
xcoordinate = newxcoor;
ycoordinate = newycoor;
name = newname;
symbol = newsymbol;
}
public int getXCoor(){
return xcoordinate;
}
public int getYCoor(){
return ycoordinate;
}
}
public class world {
private entity[] ObArray = new entity[4];
public world(){
world test = new world();
}
public void draw(){
for (int i = 0; i < 4; i++)
{
//int x = ObArray[i].getXLoc();
//int y = ObArray[i].getYLoc();
}
}
}
public class mainclass {
public static void main(String[] args){
world worldob = new world();
//entity a = new entity();
//entity b = new entity();
//entity c = new entity();
//entity d = new entity();
worldob.draw();
}
}
My draw function and main function are not finished. After the array is initialized I will be able to finish the draw method using the entity get functions.
Thanks for your help.
That is one way of doing it. You can also define all of your entities inline like this:
private entity[] ObArray = {
new entity(0,0,"Entity1",'a'),
new entity(10,10,"Entity2",'b'),
new entity(20,20,"Entity3",'c'),
new entity(30,30,"Entity4",'d')
};
A better way may be to do an ArrayList instead of an array:
private List<entity> ObArray = new ArrayList<>();
ObArray.add(new entity(0,0,"Entity1",'a');
ObArray.add(new entity(10,10,"Entity2",'b');
ObArray.add(new entity(20,20,"Entity3",'c');
ObArray.add(new entity(30,30,"Entity4",'d');
To access each element you just need to get the element from the array and either get or set the properties you need:
ObArray[0].getXCoor();
ObArray[0].setXCoor(5);
Your problem is only creating new object of world inside world's constructor which throws stack overflow error, otherwise it is fine:
public world(){ world test = new world(); //REMOVE THIS LINE
}
You simply need to initialise the array. This can be done in the world constructor.
public world()
{
for (int i = 0; i < 4; i++)
{
ObArray[i] = new entity();
}
}
Then you can access the objects in your draw method, as you've shown:
public void draw()
{
for (int i = 0; i < 4; i++)
{
int x = ObArray[i].getXCoor();
int y = ObArray[i].getYCoor();
System.out.println("x" + x);
System.out.println("y" + y);
// Manipulate items in the array
// ObArray[i].setXCoor(10);
}
}
A more complete example, with the move functions added, and the class names capitalised:
public class Entity
{
private int xcoordinate;
private int ycoordinate;
private String name;
private char symbol;
public Entity()
{
xcoordinate = 20;
ycoordinate = 30;
}
private Entity(int newxcoor, int newycoor, String newname, char newsymbol)
{
xcoordinate = newxcoor;
ycoordinate = newycoor;
name = newname;
symbol = newsymbol;
}
public int getXCoor()
{
return xcoordinate;
}
public void setXCoor(int xcoordinate)
{
this.xcoordinate = xcoordinate;
}
public int getYCoor()
{
return ycoordinate;
}
public void setYcoor(int ycoordinate)
{
this.ycoordinate = ycoordinate;
}
public static void main(String[] args)
{
World worldob = new World();
worldob.draw();
worldob.move(0, 15, 30);
worldob.move(1, 45, 0);
worldob.move(2, 23, 27);
worldob.move(3, 72, 80);
worldob.draw();
}
}
class World
{
private final Entity[] ObArray;
public World()
{
this.ObArray = new Entity[4];
for (int i = 0; i < ObArray.length; i++)
{
ObArray[i] = new Entity();
}
}
public void move(int index, int xCoor, int yCoor)
{
if (index >= 0 && index < ObArray.length)
{
Entity e = ObArray[index];
e.setXCoor(xCoor);
e.setYcoor(yCoor);
}
}
public void draw()
{
for (Entity e : ObArray)
{
int x = e.getXCoor();
int y = e.getYCoor();
System.out.println("x" + x);
System.out.println("y" + y);
}
}
}
I have a class which only allows integers with limited amount. The problem is, class is doing its work but when I use multiple objects, it only takes the last objects limitation number and applies to others.
I also couldn't get rid of static warnings.
Code is ;
public class LimitedIntegerTF extends JTextField {
private static final long serialVersionUID = 1L;
private static int limitInt;
public LimitedIntegerTF() {
super();
}
public LimitedIntegerTF(int limitInt) {
super();
setLimit(limitInt);
}
#SuppressWarnings("static-access")
public final void setLimit(int newVal)
{
this.limitInt = newVal;
}
public final int getLimit()
{
return limitInt;
}
#Override
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
#SuppressWarnings("serial")
static class UpperCaseDocument extends PlainDocument {
#Override
public void insertString(int offset, String strWT, AttributeSet a)
throws BadLocationException {
if(offset < limitInt){
if (strWT == null) {
return;
}
char[] chars = strWT.toCharArray();
boolean check = true;
for (int i = 0; i < chars.length; i++) {
try {
Integer.parseInt(String.valueOf(chars[i]));
} catch (NumberFormatException exc) {
check = false;
break;
}
}
if (check)
super.insertString(offset, new String(chars),a);
}
}
}
}
How I call it on another class ;
final LimitedIntegerTF no1 = new LimitedIntegerTF(5);
final LimitedIntegerTF no2 = new LimitedIntegerTF(7);
final LimitedIntegerTF no3 = new LimitedIntegerTF(10);
The result is no1, no2, and no3 has (10) as a limitation.
Example:
no1: 1234567890 should be max len 12345
no2: 1234567890 should be max len 1234567
no3: 1234567890 it's okay
It's because your limitInt is static, which means it has the same value for all instances of that class (What does the 'static' keyword do in a class?). Make it non-static, and each instance of your class will have their own value for it.
If you want to use limitInt in the inner class UpperCaseDocument, then make that class non-static as well. However, if you do that, each instance of UpperCaseDocument will also have an instance of LimitedIntegerTF associated with it.
It's a little bit difficult but i'll try to explain my problem. I've created a program with a superclass (RichIndustrialist) two subclasses (PredecessorRichIndustrialist and another one I didn't add) and 4 subclasses to these subclasses (CrazyRichIndustrialist and another 3). Now, the program is too difficult to explain but the problem is actually simple. My constructor is in the superclass and every subclass use it to initilize. Every time I create a new subclass object like CrazyRichIndustrialist, it resets all the already existed subclasses (from any subclass) to the value of the new object. I don't know how to fix this. Thank you in advance...
RichIndustrialist:
package Mortal;
import java.util.Random;
public class RichIndustrialist implements Mortal {
private static String Name;
private static double holdings;
private static int Alive;
public RichIndustrialist(String Rich_Name, double Rich_holdings) {
this.Name = Rich_Name;
this.holdings = Rich_holdings;
this.Alive = 1;
}
public int isAlive() {
return (this.Alive);
}
public void setHoldings(double new_holdings) {
this.holdings = new_holdings;
}
public double getHoldings() {
return (this.holdings);
}
public String getName() {
return (this.Name);
}
public void die() {
this.Alive = 0;
}
public void getHeritage(double heritage) {
this.holdings = this.holdings + heritage;
}
}
PredecessorRichIndustrialist:
package Mortal;
import java.util.Arrays;
public class PredecessorRichIndustrialist extends RichIndustrialist {
private static String Name;
private static double holdings;
private RichIndustrialist[] successors = {};
private static int Alive;
public PredecessorRichIndustrialist(String Rich_Name, double Rich_holdings) {
super(Rich_Name,Rich_holdings);
}
public void die() {
super.die();
}
public void Inheritance(double holdings, RichIndustrialist[] successors) {
int i = 0;
while (i < successors.length) {
int Alive = successors[i].isAlive();
System.out.println(Alive);
if (Alive == 0) {
removeSuccessor(successors[i]);
i++;
} else {
i++;
}
}
}
public void addSuccessor(RichIndustrialist new_successor) {
RichIndustrialist[] new_successors = new RichIndustrialist[successors.length + 1];
if (successors.length == 0) {
new_successors[0] = new_successor;
successors = new_successors;
} else {
for (int i = 0; i < successors.length; i++) {
new_successors[i] = successors[i];
}
new_successors[new_successors.length - 1] = new_successor;
}
this.successors = new_successors;
}
public void removeSuccessor(RichIndustrialist removed_successor) {
RichIndustrialist[] new_successors = new RichIndustrialist[this.successors.length - 1];
int j = 0;
for (int i = 0; i < this.successors.length; i++) {
if (!this.successors[i].equals(removed_successor)) {
new_successors[j] = this.successors[i];
} else {
j--;
}
j++;
}
}
public RichIndustrialist[] getSuccessors() {
return successors;
}
}
CrazyRichIndustrialist:
package Mortal;
import java.util.Random;
public class CrazyRichIndustrialist extends PredecessorRichIndustrialist {
private RichIndustrialist[] successors = {};
private static String Name;
private static double holdings;
private static int Alive;
public CrazyRichIndustrialist(String Rich_Name, double Rich_holdings) {
super(Rich_Name,Rich_holdings);
}
public void die() {
super.die();
Inheritance(getHoldings(),getSuccessors());
}
public void addSuccessor(RichIndustrialist new_successor) {
super.addSuccessor(new_successor);
}
public void removeSuccessor(RichIndustrialist removed_successor) {
super.removeSuccessor(removed_successor);
}
public void Inheritance (double holdings , RichIndustrialist[] successors) {
super.Inheritance(holdings, successors);
for (int i=0; i<successors.length-1; i++)
{
double random = new Random().nextDouble();
double amount = this.holdings * random;
successors[i].getHeritage(amount);
holdings = this.holdings - amount;
}
successors[successors.length-1].getHeritage(this.holdings);
this.holdings = 0;
}
public String getName(){
return super.getName();
}
public double getHoldings(){
return super.getHoldings();
}
public RichIndustrialist[] getSuccessors(){
return super.getSuccessors();
}
public void setHoldings(double new_holdings){
super.setHoldings(new_holdings);
}
public int isAlive() {
return super.isAlive();
}
public void getHeritage(double heritage) {
super.getHeritage(heritage);
}
}
Most of your fields are static. What that means is that all the instances of your classes share the same value. When you call the constructor, the static fields are modified, which affects all the existing instances.
For example:
this.Name = Rich_Name;
should actually have been written:
RichIndustrialist.Name = Rich_Name;
You can read about the difference between instance and class (or static) members in this tutorial.
The following fields should be declared as non-static. When these fields are declared as static each RichIndustrialist instance will share these fields and their assigned values. Declaring them as non-static allows each RichIndustrialist instance to have its own copy of these fields, which is autonomous from the other instances of RichIndustrialist.
private String Name;
private double holdings;
private int Alive;
Here is a good description of static from the Java Tutorial
Sometimes, you want to have variables that are common to all objects.
This is accomplished with the static modifier. Fields that have the
static modifier in their declaration are called static fields or class
variables. They are associated with the class, rather than with any
object. Every instance of the class shares a class variable, which is
in one fixed location in memory. Any object can change the value of a
class variable, but class variables can also be manipulated without
creating an instance of the class.
Your properties/variables are static. and we know static variable are shared between all the objects.
That is the reason the last object will replace the existing value of your variables
Suggestion:
change your static modifier to instance modifier
From
private static String Name;
private static double holdings;
private static int Alive;
To
private String Name;
private double holdings;
private int Alive;
I am sure your problem will resolve.
You are declaring the Name member field in all of your classes, you should only declare it in the super-class and let the other sub-classes (re)use it.
Furthermore, you declared the field as static, all instances of your class will use the same field, which is probably not what you intended, so remove the static part.
Same goes for all of your other member fields.
Note: do not start the member fields with a capital: Name should be defined and used as name. Class names on the other hand should start with a capital! This is a generically accepted Java convention and keeps things more clear/separated.