How to add an object inside another object? - java

I am trying to create a console chess game.
I have Square class and my Chessboard have 64 Square objects. Also some of these squares have Piece object. How can i add these Piece objects into the Square Objects?*
public class Square {
int column;
int row;
Piece piece;
Square(){
}
public void setRow(int row) {
this.row=row;
}
public void setColumn(int col){
this.column=col;
}
#Override
public String toString() {
// TODO Auto-generated method stub
if(1< row && row <6)
return " ";
return super.toString();
}
}

public void setPiece(Piece piece) {
this.piece = piece;
}
Adding this to your class lets you set a piece for each square. You can also define the piece in the square's constructor as this quarantees that a square always has a defined piece.

You can add these useful methods to your Square class in order to set the various pieces between all the squares you want.
/**
* #param piece to set on the actual square.
*/
public void setPiece(Piece piece) {
this.piece = piece;
}
/**
* Removes the actual piece on the square, if it exists.
*/
public void removePiece() {
if(piece != null)
piece = null;
}
/**
* #param square where to move the piece on the actual square.
* #return true if the piece were moved correctly, false otherwise.
* e.g. of a false return is when the piece on the actual square is not present, in other words, it is null.
*
* ATTENTION: Obviously the moved piece is removed from the actual square.
*/
public boolean movePiece(Square square) {
if(piece != null) {
square.setPiece(piece);
removePiece();
return true;
} else
return false;
}

Related

Objects' variables changed by method in another class [duplicate]

This question already has answers here:
How to make a method in a class, manipulate variables in another class?
(2 answers)
Closed 5 years ago.
I created a simple method in my CardGames class that replicates a card game to play around with conditional statements. I call the method from a separate Player class because the player earns/loses points based on the card. I want the method to be able to change the player objects points variable.
What I want to have happen is when the playSimpleCardGame gets called by the Player object, the method changes the Player object's points.
But when I run it the points do not change. I've tried extending/implementing both classes (i.e. shooting in the dark). I also created an instance variable points in the CardGames class but then the Player object does not have points as a variable. What am I missing?
public class Player
{
private int points;
public static void main(String[] args)
{
CardGames steve = new CardGames();
System.out.println(steve.playSimpleCardGame("red"));
System.out.println(steve.playSimpleCardGame("red"));
System.out.println(steve.playSimpleCardGame("black"));
System.out.println(steve.playSimpleCardGame("black"));
System.out.println(steve.points);
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color)
{
if (color.equalsIgnoreCase("red"))
return points = points + 1;
else
return points = points - 2;
}
}
public class Player
{
private int points;
public Player(){
points=0;
}
public static void main(String[] args)
{
CardGames game = new CardGames();
Player steve = new Player();
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(steve.points);
}
public int getPoints() {
return points;
}
public void addPoints(int p) {
this.points = points + p;
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color, Player player)
{
if (color.equalsIgnoreCase("red"))
{
player.addPoints(1);
return player.getPoints();
}
else
{
player.addPoints(-2);
return player.getPoints();
}
}
}
Firstly, there is no need to extend CardGames class by the Player class. Secondly, even if you wish to do it, it will be a bad design. I won't go into the design part. The following code should answer your problem :
public class Player
{
public Integer points;
public Player(){
points=0;
}
public static void main(String[] args)
{
CardGames game = new CardGames();
Player steve = new Player();
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(steve.points);
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color, Player player)
{
if (color.equalsIgnoreCase("red"))
return player.points = player.points + 1;
else
return player.points = player.points - 2;
}
}

Java Generics - Multiple Questions (Type not within bounds, Warnings)

I have a few classes that I need to be generic. I have the following class DataSet that I want to be able to generate an average and maximum of any sort of Objects passed into class that implements my measurable interface or my Measurer interface.
When I go to test my code, I get the error that my type is not within bounds. Any ideas? When I exclude the Measurer from the DataSet, the test compiles. I am not sure if I made the DataSet correctly Generic.
DataSet.java
public class DataSet<T extends Measurable<Double> & Measurer<Double>>//
{
/**
Constructs an empty data set.
*/
public DataSet()
{
this.sum = 0;
this.count = 0;
this.maximum = null;
}
/**
Adds a data value to the data set.
#param x a data value
*/
public void add(T x)
{
sum = sum + x.getMeasure();
if (count == 0 || maximum.getMeasure() < x.getMeasure())
maximum = x;
count++;
}
/**
Gets the average of the added data.
#return the average or 0 if no data has been added
*/
public double getAverage()
{
if (count == 0) return 0;
else return sum / count;
}
/**
Gets the largest of the added data.
#return the maximum or 0 if no data has been added
*/
public T getMaximum()
{
return maximum;
}
private double sum;
private T maximum;
private int count;
}
DataSetTest.java
import java.awt.Rectangle;
public class DataSetTest
{
public static void main(String[] args)
{
DataSet<BankAccount<Double>> ds1 = new DataSet<>();
BankAccount<Double> ba1 = new BankAccount<>(100.00);
BankAccount<Double> ba2 = new BankAccount<>(300.00);
}
}
BankAccount.java
public class BankAccount<T> implements Measurable<T>
{
public BankAccount()
{
balance = null;
}
public BankAccount(T balance)
{
this.balance = balance;
}
public T getMeasure()
{
return balance;
}
private T balance;
}
Measurable.java
/**
Describes any class whose objects can be measured.
*/
public interface Measurable <T>
{
/**
Computes the measure of the object.
#return the measure
*/
T getMeasure();
}
Measurer.java
/**
Describes any class whose objects need a measurer.
*/
public interface Measurer <T>
{
/**
Computes the measurer of the object.
#return the measurer
*/
T getMeasurer(T anObject);
}
rectangleShape.java
import java.awt.Rectangle;
/**
Concrete Class RectangleMeasurer
#param Takes object as parameter. Overloads measurer class.
#return Returns the area of a object passed in.
*/
public class rectangleShape<T> implements Measurer<T>{
public T getMeasurer(T anObject)
{
Rectangle aRectangle = (Rectangle) anObject;
Double area = aRectangle.getWidth() * aRectangle.getHeight();
//#SuppressWarnings("unchecked")
a = (T)area;
return a;
}
private T a;
}
The type bounds <T extends Measurable<Double> & Measurer<Double>> imply the parameter extends Measurable AND Measurer, but you want that to be OR. You can't do that with generic parameter syntax.
You can however have overloaded methods in DataSet.
public add(Measurable<Double> m) {
//...
}
public add(Measurer<Double> m) {
//...
}
Or you can do runtime type checking, although that is not the most advisable.
public add(Object o) {
if (o instanceof Measurable) {
//...
} else if (o instanceof Measurer) {
//...
}
}
Basically, your use case does not require a type parameter on the class. You are trying to make the problem fit your solution rather than the other way around.

Code Wont Run, Got Strange Error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have got some code and it all seems to work apart from one error that appears. This stops the whole program running. Please could you have a look at the code and see what the issue is. This is a space invaders game and this is the class that contains the public static void main.
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25;
public static int ALIEN_WIDTH = 15;
private int leftPosition = 0;
private int heightPosition = 0;
private boolean hitState = false;//Whether this alien has already been shot
private Image alienImage = null;
SpaceInvaders spaceInvaders = null;
/**
*
*/
public Alien(Image ai, SpaceInvaders si) {
alienImage = ai;
spaceInvaders = si;
}
/**
* Returns whether ythe alien had been hit
*/
public boolean hasBeenHit() {
return hitState;
}
/**
* Check if a shot fired hit an alien
*/
public boolean hitAlien(int x, int y) {
//Is the alien currently alive?
if (hitState) {
//If it's alreay been shot then return false;
return false;
}
//First lets check the X range
if ((x >= leftPosition) && (x <= (leftPosition+ALIEN_WIDTH))) {
//X is ok, now lets check the Y range
if ((y >= heightPosition) && (y <= (heightPosition+ALIEN_HEIGHT))) {
//We shot an alien!
hitState = true;
return true;
}
}
return false;
}
/**
* Set the position of the alien on the screen
*/
public void setPosition(int x, int y) {
leftPosition = x;
heightPosition = y;
}
/**
* Returns the current x position of the alien
*/
public int getXPos() {
return leftPosition;
}
/**
* Returns the current x position of the alien
*/
public int getYPos() {
return heightPosition;
}
/**
* Draw the image of the Alien
*/
public void drawAlien(Graphics g) {
if (!hitState) {
g.setColor(Color.red);
g.fillRect(leftPosition, heightPosition, ALIEN_WIDTH, ALIEN_HEIGHT);
}
}
}
}
}
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "}" to complete MethodBody
at Alien.main(Alien.java:3)
You seem to be mis-understanding the basics of Java syntax. Specifically, you cannot define your class's members and methods inside main() the way you are attempting to do:
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25; // you can't put this here
public static int ALIEN_WIDTH = 15; // you can't put this here
private int leftPosition = 0; // you can't put this here
private int heightPosition = 0; // you can't put this here
//etc
To get this to compile, you need to close main() and delete all the extra } you have at the end of your code:
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25;
public static int ALIEN_WIDTH = 15;
//etc
You'll also need to add some code to main() before your program actually does anything.
I would suggest that before you continue your current program you read some of the excellent tutorials online. A good place to start is The Java™ Tutorials on the oracle website.
Look at the Trails Covering the Basics section and work your way through Getting Started and Learning the Java Language before doing anything else.

Return an iterator

Searching for info about the iterator, I found only examples that showed how to iterate over a collection, and not returning the Iterator, like I want to do.
I am practicing for the exam, so I'm trying out some programming excercises to prepare myself, and this one is about the iterator pattern.
I want to implement the getKnightPositionIterator, . You can see the code below. This code is not mine, I found this.
package iterator;
import java.util.*;
public class Position {
/** return an iterator that will return all positions
* that a knight may reach from a given starting position.
*/
public static Iterator<Position> getKnightPositionIterator(Position p) {
return null;
}
/** create a position.
* #param r the row
* #param c the column
*/
public Position(int r, int c) {
this.r = r; this.c = c;
}
protected int r;
protected int c;
/** get the row represented by this position.
* #return the row.
*/
public int getRow() { return r; }
/** get the column represented by this position.
* #return the column.
*/
public int getColumn() { return c; }
public boolean equals(Object o) {
if (o.getClass() != Position.class) { return false; }
Position other = (Position) o;
return r==other.r && c==other.c;
}
public int hashCode() {
// works ok for positions up to columns == 479
return 479*r+c;
}
public String toString() {
return "["+r+","+c+"]";
}
}
How ever, I figure that I have to create an Iterator to return, so, so far, this is my attemp.
public static Iterator<Position> getKnightPositionIterator(Position p) {
Iterator<Position> knightPosIter = Position.getKnightPositionIterator(p);
for(Iterator<Position> positions = knightPosIter; positions.hasNext(); ) {
//What should I write here?
}
return knightPosIter;
}
First, make your class implement Iterable interface
public class Position implements Iterable<Position>
and write the public Iterator<Positions> iterator(); method as outlined below instead of providing a static method in your example.
As you actually need to compute a collection of reachable positions in one way or another, you will need a structure to hold it. Any such structure will normally be iterable and, thus, will have an iterator method. So a lazy implementation could look like this:
#Override
public Iterator<Position> iterator()
{
// make sure this returns e.g. Collections.unmodifiableList
Collection<Position> positions = computeReachablePositions();
return positions.iterator();
}
In case you have some other structure to compute and store your positions that is not iterable (not advisable), implement an iterator from scratch as follows (an array of positions assumed):
#Override
public Iterator<Position> iterator()
{
// must be final to be accessible from the iterator below
final Position[] positions = computeReachablePositions();
return new Iterator<Position>() {
int index = 0;
#Override
public boolean hasNext()
{
return index < positions.length;
}
#Override
public Position next()
{
if (hasNext())
{
Position value = positions[index];
index++;
return value;
}
throw new NoSuchElementException("No more positions available");
}
#Override
public void remove()
{
throw new UnsupportedOperationException("Removals are not supported");
}};
}

External Method call help

So what im trying to do is to call an external method upon an object, its a bit trickier than I expected and am having problems properly implementing it.
The method is:
attack(Player victim)
The method needs to call a hit() method on an object; then if the hit() method was successful (test this through a boolean?):
use an if statement to call a damage() method upon the object to determine the damage
call takeDamage() upon (PlayerVictim) to inflict the damage.
Here's the player class that ive coded so far; the attack() method is at the bottom.
My main question is how to use an external method(s) damage() on the currentWeapon and takeDamage() on Player Victim
public class Player
{
private String myPlayerName;
private Weapon myWeapon;
private int myCurrentHealth;
private int myMaxHealth;
private int myNumPotions;
/**
* Constructor initializing class Player
* Parameters of the player should be:
* player name, players initial health, the players weapon.
*/
public Player(String myPlayer, int initialHealth, Weapon currentWeapon) {
myPlayerName = myPlayer;
this.myWeapon = currentWeapon;
myMaxHealth = 30;
myCurrentHealth = initialHealth;
myNumPotions = 0;
}
/**
* Attack method which attacks opposing player
* with current equipped weapon.
*/
public void attack(Player victim) {
currentWeapon.hit();
if (boolean currentWeapon.hit() = true) {
currentWeapon.damage(int dam);
return dam;
}
Player victim.takeDamage(int damage);
}
}
and the weapon class:
import java.util.Random;
public class Weapon
{
private int myHitProb;
private int myMaxDamage;
private Random myRNG;
/**
* Create a new weapon with a hit probability and damage
*/
public Weapon(int hitProb, int damage) {
myHitProb = hitProb;
myMaxDamage = damage;
myRNG = new Random();
}
public boolean hit() {
int r = myRNG.nextInt(100);
if (r < myHitProb) {
return true;
}
else {
return false;
}
}
public int damage() {
int dam = myRNG.nextInt(myMaxDamage) + 1;
return dam;
}
}
Your attack() method may be many things, but compilable java it is not.
Perhaps this is what you meant:
public void attack(Player victim) {
if (currentWeapon.hit()) {
victim.takeDamage(currentWeapon.damage());
}
}
Try to remember this guideline: If it seems hard, you're probably doing it the wrong way (unless you're working on the Mars Lander program :) )

Categories

Resources