Basic Object Oriented Design java - java

I really don't understand the principle of Object Oriented Design??
So I have classes
Map class holds rooms and connects all of rooms , places all of hazards randomly into rooms, return the particulate room, and return the random rooms.
and
Player class that play turns, move player from room to another, shoot into rooms and play games.
also
Room class as follow.
import java.util.ArrayList;
public class Room
{
private int myRoomID;
private ArrayList<Room> myNeighbours;
private boolean myHasBats;
private boolean myHasPit;
private boolean myHasWumpus;
public Room(int id) {
myRoomID = id;
myNeighbours = new ArrayList<Room>();
}
public int getRoomID() {
return myRoomID;
}
public ArrayList<Room> getNeighbours() {
return myNeighbours;
}
public void connectTo(Room room) {
myNeighbours.add(room);
}
public boolean hasBats() {
return myHasBats;
}
public void setHasBats(boolean flag) {
myHasBats = flag;
}
public boolean hasPit() {
return myHasPit;
}
public void setHasPit(boolean flag) {
myHasPit = flag;
}
public boolean hasWumpus() {
return myHasWumpus;
}
public void setHasWumpus(boolean flag) {
myHasWumpus = flag;
}
public void checkBats() {
boolean bats = false;
for (Room r : myNeighbours) {
if (r.hasBats()) {
bats = true;
}
}
if (bats) {
System.out.println("I hear squeaking!");
}
}
public void checkPit() {
boolean pit = false;
for (Room r : myNeighbours) {
if (r.hasPit()) {
pit = true;
}
}
if (pit) {
System.out.println("I feel a draft!");
}
}
public void checkWumpus() {
boolean wumpus = false;
for (Room r : myNeighbours) {
if (r.hasWumpus()) {
wumpus = true;
}
}
if (wumpus) {
System.out.println("I smell a wumpus!");
}
}
public boolean enter(Player player) {
System.out.println("You are in Room " + myRoomID);
System.out.print("Exits lead to rooms");
for (Room r : myNeighbours) {
System.out.print(" " + r.getRoomID());
}
System.out.println();
checkBats();
checkPit();
checkWumpus();
if (myHasBats) {
System.out.println("A flock of bats picks you up and carries you off to another room!");
return player.moveRandom();
}
else if (myHasPit) {
System.out.println("You fall into a bottomless pit!");
return true;
}
else if (myHasWumpus) {
System.out.println("You have been eaten by a wumpus!");
return true;
}
return false;
}
public boolean shoot()
if (myHasWumpus) {
System.out.println("You killed the Wumpus!");
return true;
}
else {
System.out.println("Your arrow falls with a clatter to the floor!");
return false;
}
}
And I want to change this so that the wumpus needs to be shot more than once (you choose how many times) to be killed. Each time it is shot it runs to a random neighbouring room (not the one the player is in).
I am assuming that I need to change public boolean shoot() method into loop and call public Room getRandomRoom() as below.
But I really don't understand how to do this, especially because the use of boolean method is very confusing to me.
Does anyone know where I can find a information to learn the basic's of Object Oriented Design?
public Room getRandomRoom() {
Random rng = new Random();
int i = rng.nextInt(Map.NUM_ROOMS);
return myRooms.get(i);
}
Later on we are going to use implements in the class to separate all of hazards into classes. but for not they are all in Map and Room class.

Well without a wumpus class that's going to be messy and limited and even more inefficient. Your problem isn't that you don't get OO, it's that you are being restricted from using it.
Without out the class.
You are goingto have to add a myWumpusShotCount to room
Then in your shoot function, add 1 to it, test to see if it's 3 and if so kill it else random choose a room and set hasWumpus and WumpusShotCount in it
If you had a wumpus class it would have a property room , and another for how many bullets it had shipped and a behaviour when shot, ie the state of the wumpus and the behaviours of wumpus would be implemented by wumpus, not room. That's OO.

With the help of Tony Hopkinson, I have come up with this code but it doesn't compile yet. It says can not find symbol - method getRandomRoom() To call the methodgetRandomRoom();` from Map class.
To send wumpus to the room another room randomly
public boolean shoot() {
if (myHasWumpus) {
myWumpusShotCount = 3;
for(int i = 0; i< myWumpusShotCount; i++){
if(myWumpusShotCount<=i){
System.out.println("You killed the Wumpus!");
return true;
}
else {
Room wRoom = getRandomRoom();
System.out.println("You killed the Wumpus!");
return false;
myWumpusShotCount++;
}
System.out.println("Your arrow falls with a clatter to the floor!");
return false;
}
System.out.println("You killed the Wumpus!");
return true;
}
}
System.out.println("Your arrow falls with a clatter to the floor!");
return false;
}

Related

Issue is Java Main class..its not running properly

I have 7 classes(shown in pick below) with main method class for testing is Animalstuff class. When I'm running the code its getting hung and not moving any where. Need your help to solve this.At the end I want to run using Junit.
classes all
running Animalstuff class, see below it hang and not moving forward.
hung
here is the code for complete Animalstuff class.
/**
*
*/
import java.util.ArrayList;
import java.util.Scanner;
public class AnimalStuff {
// main function
public static void main(String[] args) {
// for taking inputs
Scanner in = new Scanner(System.in);
// arrayList to store all the animals
ArrayList<Animal> myList = new ArrayList<Animal>();
int ch;
// Loop until user chooses to quit
do {
// print menu
System.out.println("Menu");
System.out.println("1. Add animal");
System.out.println("2. Print");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
ch = in.nextInt();
// if user chooses to add animal to list
if(ch==1) {
// input the kind/name of animal
in.nextLine();
String word;
System.out.print("Enter name of animal: ");
word = in.nextLine();
// create object of that kind
Animal obj = Animal.newInstance(word);
// if user entered invalid animal, print message
if(obj==null) {
System.out.println("Animal doesn't exist.");
}
// else add to the list
else {
myList.add(obj);
}
}
// if user chooses to see information of all the
// animals in the list
else if(ch == 2) {
for(int i=0;i<myList.size();i++) {
myList.get(i).print(true);
}
}
// if user chooses to quit
else {
System.out.println("See you soon!");
}
}while(ch != 3);
}
}
Below is the code for Animal class
import java.util.ArrayList;
import java.util.Scanner;
public class Animal {
// variables
public String kind;
public String integument;
public boolean fast;
// private constructor to avoid plain animals
private Animal() {
}
// public argument constructor for Mammal and Bird class to
// call
public Animal(String kind, boolean fast) {
this.kind = kind;
this.fast = fast;
}
// movement method
public String movement() {
if(fast) {
return "I run on four legs.";
}
else {
return "I walk on four legs.";
}
}
// sound method
public String sound() {
return "";
}
// method to print all the information about the animal
public void print(boolean fast) {
String move = "";
if(fast)
move = "fast";
else
move = "slowly";
System.out.println("I am a "+kind);
System.out.println(" I have "+integument);
System.out.println(" When I go "+move+", "+movement());
System.out.println(" The sound I make is "+sound());
}
// method to return the animal object of type kind
public static Animal newInstance(String kind) {
Animal obj;
boolean correct = false;
if(kind.toLowerCase().equals("cow")) {
obj = new Cow();
Cow cow = new Cow();
if(obj.equals(cow)) {
correct = true;
}
}
else if(kind.toLowerCase().equals("duck")) {
obj = new Duck();
Duck duck = new Duck();
if(obj.equals(duck)) {
correct = true;
}
}
else if(kind.toLowerCase().equals("parrot")) {
obj = new Parrot();
Parrot parrot = new Parrot();
if(obj.equals(parrot)) {
correct = true;
}
}
else if(kind.toLowerCase().equals("whale")) {
obj = new Whale();
Whale whale = new Whale();
if(obj.equals(whale)) {
correct = true;
}
}
else {
return null;
}
if(correct) {
System.out.println("Correct object is formed.");
}
else {
System.out.println("Wrong object is formed.");
}
return obj;
}
// Function to check if two methods are same, i.e., this function
// checks whether the object formed is correct or not
public boolean equals(Animal obj) {
if(this.kind.equals(obj.kind)) {
if(this.integument.equals(obj.integument)) {
if(this.movement().equals(obj.movement())) {
if(this.sound().equals(obj.sound())) {
return true;
}
}
}
}
return false;
}
}
Please let me know whats worng in this and how I can fix. The other classes are very small if need I can give code for those as well.
Thanks
Enter your choice:
If you are getting this line in the console then it's asking for the input ch. Enter your input and you'll proceed further.

Which Object Oriented design is a better pick when one subclass calls another?

In my scenario, we offer multiple plans to customers. (planA, planB, planC etc.) planA is lower than planB and planB is lower than planC. A customer can move from lower plan to higher plan but not vice-versa. If a customer is on planA and wants to 'activate' planB, then planA must be cancelled. Essentially, a plan can be 'activated' and 'deactivated'. I had 2 designs in mind.
interface Plan {
activate();
deactivate();
}
This interface will be inherited by each plans' (planA, planB, planC, etc). The activate method would be inherited and look something like this:
activate() {
Plan planToCancel = getLowerGradePlanToCancel()
planToCancel.cancel();
// perform business logic to activate plan.
}
Option B is something similar to strategy pattern: I have 2 interfaces:
interface Activate {
activate();
}
interface Deactivate {
deactivate()
}
Each of the plans will inherit those interfaces. Then my business logic would look something like this:
activatePlan(planName, planToDeactivate) {
Activate activate = Factory.getActivateInstanceForPlan(planName);
DeActivate dectivate = Factory.getActivateInstanceForPlan(planToDeactivate);
deactivate.deactivate();
activate.activate();
}
Of the two designs which one is more appropriate (Object Oriented) and why ? The only thing in code that is likely to change is more plans will be added in future.
You have 3 plans. Plan C can't go higher and similarly plan A can't go lower. Plan B can do both operations. Use one interface and put activate and deactivate methods there. You already mentioned that on option A. Use template pattern there to give an opportunity to change their behaviours for your plans. This will be appropriate if you will add another plans later on. This will help you a lot when you add another plans.
If you will have only three plans, then second option is more appropriate. Since you have only 3 plans and only one of them using activate and deactivate together, then you don't need to implement both of the methods, interfaces. This will decrease the dependencies of your code.
Pick the best choice for your case.
I have a different approach in mind where you have a class that manages all the plans, while plan interface is encapsulated and only reveals the necessary of its API.
I think this approach will have minimal code modification for each added Plan, moreover, it can prevent user from making mistakes (e.g. downgrading a plan).
The essential interfaces:
interface Plan {
public Plan next();
public boolean isActivated();
// for debug purposes
public String planDescription();
}
interface PlansManager {
public Plan nextPlan(Plan current);
}
The basic idea is to have some SemiConcretePlan class which implements the static (mutual) behaviour in all plans, the public API is next & isActivated while activate and cancel methods private (you don't want the user to cancel a plan without switching to the next or to activated a cancelled one be keeping a previous Plan pointer on it) and only the PlansManager or the Plan itself will handle the activation and cancellation, PlansManager activates the first plan and returns it and next method uses PlansManager to get the next and only the SemiConcertePlan activate the current and cancels the previous Plan.
Here the SemiConcertePlan:
abstract class SemiConcretePlan implements Plan {
private PlansManager m_plansManager;
private boolean m_isActivated;
private int m_id;
private static int s_idGenerator = 0, s_firstActivatedId = 1;
public SemiConcretePlan(PlansManager plansManager){
m_plansManager = plansManager;
m_id = generateId();
m_isActivated = (m_id == s_firstActivatedId);
}
private int generateId() {
return ++s_idGenerator;
}
private void activatePlan() {
this.m_isActivated = true;
}
private void cancelPlan() {
this.m_isActivated = false;
}
public boolean isActivated() {
return this.m_isActivated;
}
public Plan next() {
this.cancelPlan();
SemiConcretePlan nextPlan = (SemiConcretePlan) m_plansManager.nextPlan(this);
nextPlan.activatePlan();
return nextPlan;
}
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || !(other instanceof SemiConcretePlan) || this.hashCode() != other.hashCode())
return false;
SemiConcretePlan otherPlan = ((SemiConcretePlan) other);
if (m_id != ((SemiConcretePlan) otherPlan).m_id)
return false;
return true;
}
public abstract int hashCode();
public abstract String planDescription();
}
planDescription method is an example of dynamic method, hashCode is needed for class PlansManager to hash plans in map which map current plan to higher (next) plan.
Here is the AscedingPlansManager class:
class AscedingPlansManager implements PlansManager{
private List<Plan> m_plansList;
private Map<Plan, Plan> m_planToHigherPlanMapping;
public AscedingPlansManager() {
m_plansList = new LinkedList();
m_planToHigherPlanMapping = new HashMap();
Plan[] plans = {
new PlanA(this),
new PlanB(this),
new PlanC(this),
new PlanD(this)
};
for(int i = 0; i < plans.length - 1; ++i) {
m_plansList.add(plans[i]);
m_planToHigherPlanMapping.put(plans[i], plans[i+1]);
}
m_plansList.add(plans[plans.length - 1]);
m_planToHigherPlanMapping.put(plans[plans.length - 1], plans[plans.length - 1]);
}
public Plan nextPlan(Plan current) {
return m_planToHigherPlanMapping.getOrDefault(current, null);
}
private void activatePlan(Plan plan) {
try {
Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("activatePlan");
privateActivateMethod.setAccessible(true);
privateActivateMethod.invoke(plan);
} catch(Exception e) {
e.printStackTrace();
}
}
public void cancelAll() {
for(Plan plan: m_plansList)
try {
Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("cancelPlan");
privateActivateMethod.setAccessible(true);
privateActivateMethod.invoke(plan);
} catch(Exception e) {
e.printStackTrace();
}
}
public Plan firstPlan() {
Plan first = m_plansList.get(0);
this.activatePlan(first);
return first;
}
public boolean[] plansToActivationState() {
boolean[] ret = new boolean[m_plansList.size()];
int index = 0;
for(Plan plan: m_plansList)
ret[index++] = plan.isActivated();
return ret;
}
}
I know that this is huge code, but I think it will make add plans easy, you will only need to change the hashCode method, the sequence of the plans can be changed in the constructor of AscedingPlansManager or creating a different manger class from scratch.
Here is the full code, you can see how little changes I needed to do for class PlanD:
import java.util.;
import java.lang.reflect.;
interface Plan {
public Plan next();
public boolean isActivated();
// for debug purposes
public String planDescription();
}
interface PlansManager {
public Plan nextPlan(Plan current);
}
abstract class SemiConcretePlan implements Plan {
private PlansManager m_plansManager;
private boolean m_isActivated;
private int m_id;
private static int s_idGenerator = 0, s_firstActivatedId = 1;
public SemiConcretePlan(PlansManager plansManager){
m_plansManager = plansManager;
m_id = generateId();
m_isActivated = (m_id == s_firstActivatedId);
}
private int generateId() {
return ++s_idGenerator;
}
private void activatePlan() {
this.m_isActivated = true;
}
private void cancelPlan() {
this.m_isActivated = false;
}
public boolean isActivated() {
return this.m_isActivated;
}
public Plan next() {
this.cancelPlan();
SemiConcretePlan nextPlan = (SemiConcretePlan) m_plansManager.nextPlan(this);
nextPlan.activatePlan();
return nextPlan;
}
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || !(other instanceof SemiConcretePlan) || this.hashCode() != other.hashCode())
return false;
SemiConcretePlan otherPlan = ((SemiConcretePlan) other);
if (m_id != ((SemiConcretePlan) otherPlan).m_id)
return false;
return true;
}
public abstract int hashCode();
public abstract String planDescription();
}
class AscedingPlansManager implements PlansManager{
private List<Plan> m_plansList;
private Map<Plan, Plan> m_planToHigherPlanMapping;
public AscedingPlansManager() {
m_plansList = new LinkedList();
m_planToHigherPlanMapping = new HashMap();
Plan[] plans = {
new PlanA(this),
new PlanB(this),
new PlanC(this),
new PlanD(this)
};
for(int i = 0; i < plans.length - 1; ++i) {
m_plansList.add(plans[i]);
m_planToHigherPlanMapping.put(plans[i], plans[i+1]);
}
m_plansList.add(plans[plans.length - 1]);
m_planToHigherPlanMapping.put(plans[plans.length - 1], plans[plans.length - 1]);
}
public Plan nextPlan(Plan current) {
return m_planToHigherPlanMapping.getOrDefault(current, null);
}
private void activatePlan(Plan plan) {
try {
Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("activatePlan");
privateActivateMethod.setAccessible(true);
privateActivateMethod.invoke(plan);
} catch(Exception e) {
e.printStackTrace();
}
}
public void cancelAll() {
for(Plan plan: m_plansList)
try {
Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("cancelPlan");
privateActivateMethod.setAccessible(true);
privateActivateMethod.invoke(plan);
} catch(Exception e) {
e.printStackTrace();
}
}
public Plan firstPlan() {
Plan first = m_plansList.get(0);
this.activatePlan(first);
return first;
}
public boolean[] plansToActivationState() {
boolean[] ret = new boolean[m_plansList.size()];
int index = 0;
for(Plan plan: m_plansList)
ret[index++] = plan.isActivated();
return ret;
}
}
class PlanA extends SemiConcretePlan {
public PlanA(PlansManager plansManager) {
super(plansManager);
}
public int hashCode() {
return 1;
}
public String planDescription() {
return "This is PlanA";
}
}
class PlanB extends SemiConcretePlan {
public PlanB(PlansManager plansManager) {
super(plansManager);
}
public int hashCode() {
return 2;
}
public String planDescription() {
return "This is PlanB";
}
}
class PlanC extends SemiConcretePlan {
public PlanC(PlansManager plansManager) {
super(plansManager);
}
public int hashCode() {
return 3;
}
public String planDescription() {
return "This is PlanC";
}
}
class PlanD extends SemiConcretePlan {
public PlanD(PlansManager plansManager) {
super(plansManager);
}
public int hashCode() {
return 4;
}
public String planDescription() {
return "This is PlanD";
}
}
public class Main{
public static void main(String []args){
AscedingPlansManager ascedingPlansManager = new AscedingPlansManager();
Plan currentPlan = ascedingPlansManager.firstPlan();
int i = 0, maxIterations = 5;
while((++i) <= maxIterations) {
System.out.println(currentPlan.planDescription());
System.out.println(Arrays.toString(ascedingPlansManager.plansToActivationState()));
currentPlan = currentPlan.next();
}
ascedingPlansManager.cancelAll();
System.out.println("After canceling all plans");
System.out.println(Arrays.toString(ascedingPlansManager.plansToActivationState()));
}
}
I still not sure of my implementation, I usually access private method in c++ with friend modifier, if you want to discuss anything feel free to do so.

Text game. How to use a bag?

Im wondering how i would go about using a bag in the game im making. The bag is supposed to hold 2 items that can be found in different rooms around the "map" and when both these items are found the game can be completed by finding the boss room. The bag is supposed to be its own java class. And how do i make the player activate these items?
rum4 and rum6 is the item rooms for anyone wondering.
(I dont want anyone to finish this game for me, i just want some help)
//Sorry for the swedish text.
//This is obviously not all of the code but the rest of it is not neccessary.
import java.util.Scanner;
public class Spel
{
public static void main(String[] args) {
Rum start = new Rum("Du är i en mörk och fuktig källare."," En källare. ");
Rum rum1 = new Rum("Du är mitt i en snöstorm!", "En snöstorm. ");
Rum rum2 = new Rum("Du hittade ett svärd!", "Ett hus. ");
Rum rum3 = new Rum("Du gick in i en fälla, slå över 3 för att fly norrut.", "En skog. ");
Rum rum4 = new Rum("Jaha... här fanns det ingenting.", "En äng. ");
start.north = rum1;
start.east = rum2;
start.south = rum3;
rum1.south = start;
rum1.east = rum4;
rum2.west = start;
rum2.north = rum4;
rum3.fälla = new trap();
rum3.north = start;
rum4.west = rum1;
rum4.south = rum2;
Rum current = start;
while(true) {
System.out.println(current);
System.out.println("Vart vill du gå? (n,s,v,o)");
char c = new Scanner(System.in).next().charAt(0);
switch(c) {
case 'n':
current = current.north;
break;
case 's':
current = current.south;
break;
case 'v':
current = current.west;
break;
case 'o':
current = current.east;
break;
}
if (current.fälla != null){
current.fälla.rulla();
}
// if (monster){
// System.out.println("Du kan nu döda monsteret");
if(current == null) {
System.out.println("Du ramlar av världen och dör †††");
System.out.println("Försök igen");
current = start;
}
}
I would create a class Bag with two Items
public class Bag {
Item item1;
Item item2;
}
public class Item {
<any item properties here>
}
In that case, I believe you need a class for Item, and types of items for the specific effects.
public abstract class Item {
public abstract void useItemOn(Entity target);
}
public class Entity {
private int maxHitPoints;
private int hitPoints;
private boolean isDead;
...
public void inflictDamage(int damage) {
hitPoints -= damage;
if(hitPoints < 0) {
this.isDead = true;
}
}
public void heal(int healPoints) {
hitPoints += healPoints;
if(hitPoints > maxHitPoints) {
this.hitPoints = maxHitPoints;
}
}
...
}
public class Player extends Entity {
...
}
public class Enemy extends Entity {
...
}
public Bomb extends Item {
#Override
public void useItemOn(Entity target) {
target.inflictDamage(20);
}
}
public Potion extends Item {
#Override
public void useItemOn(Entity target) {
target.heal(20);
}
}
Then
public class Bag {
private List<Item> items;
public Bag() {
this(new ArrayList<Item>());
}
public Bag(List<Item> items) {
this.items = items;
}
public List<Item> getItems() {
return items;
}
}
You can of course use smarter way to store Items to not mix them up, as you still need to figure out if something is a potion or a bomb.
But anyways, using it is simple, you need to take an item from the list, use it on an entity, then remove it from the list if it's a consumable.
Can someone find the boss room before they found the items? If no: how do you prevent it?
What you have to do when using my solution:
Create the bag at the begin of the game
Whenever one of the items was found: call the setFirstItemFound or setSecondItemFound method.
I don't know how you want to enable the boss room, but you can check if i should be findable by using the method "isBothItemsFound()"
Please notice, that this solution only works if there are only two items needed. If later like 10 items needed i would recommend you to make use of a hashTbale, a list or any equal "stacking" classes
public class Bag {
private static boolean firstItemFound = false;
private static boolean secondItemFound = false;
public Bag() {
super();
firstItemFound = false;
secondItemFound = false;
}
/* Sets the status to of the first Item to found */
public static void setFirstItemFound() {
firstItemFound = true;
}
/* Checks if the first item has been found */
public static boolean isFirstItemFound() {
return firstItemFound;
}
/* Sets the status to of the second Item to found */
public static boolean isFSecondItemFound() {
return secondItemFound;
}
/* Checks if the second item has been found */
public static void setSecondItemFound() {
secondItemFound = true;
}
/* Checks if both items has been found */
public static boolean isBothItemsFound() {
boolean bothItemsFound = false;
if (firstItemFound && secondItemFound){
bothItemsFound = true;
}
return bothItemsFound;
}
/* Sets the status to of both Items to not found */
public static void clearBag() {
firstItemFound = false;
secondItemFound = false;
}
}
You could maybe create some Player class to store all player data, and put Bag in it to hold items for example in:
HashMap<String, Item> itemsByName;
and always check when adding a new item to it if size 2 is not over exceeded.

monopoly property multiple owner

I'm creating a Monopoly program in Java and I run into a problem: When a player lands on a Property always get's to buy it, even if it's already owned.
Here are the two pieces of code that come in question:
Property class:
class Property{
public int ownerID = -1;
public Player owner;
public boolean isOwned;
public int price, rent; // defined in Constructor
public void onLanded(Player p){
if(OwnerID < 0){
p.offerProperty(this);
} else if(ownerID != p.getID(){
p.transfer(-rent);
owner.transfer(rent);
System.ou.println("bla bla");
} else {
System.out.println("bla bla");
}
}
public void buy(Player p){
p.transfer(-price);
setOwner(p);
p.assets.add(this);
}
public void setOwner(Player p){
owner = p;
ownerID = p.getID();
isOwner = true;
}
}
class Player:
class Player{
int id, money; // defined in Constructor
ArrayList<Property> assets = new ArrayList<Property>();
public void offerProperty(Property p){
if(money >= p.getPrice()){
System.out.println("wanna bu?");
String inputAnswer = scanner.next();
if(agreed(inpuAnswer))
p.buy(this);
}
}
public boolean agreed(String s){
if(s.equals("yes") return true;
return false;
}
public int getID(){
return id;
}
public void transfer(int amount){
money += amount;
}
}
Now, as I said, every time I run the game I get that if a player lands on a already owned property, he get the possibility to buy it instead of having to pay the rent to the owner. I have been looking for solutions for days and I also tried some other approach to the problem but always unsuccessful. Does anybody have an idea how to solve this issue?
In class Property, change this method:
public void buy(Player p) {
if (owner == null) {
p.transfer(-price);
setOwner(p);
p.assets.add(this);
}
}
I found my bug, and it wasn't actually in the piece of code I wrote in the question. :)
The bug was that every time a player moves, he creates a new board and moves on it, so the property is always not owned.

Arraylist Search and Show object methods confusion

The two methods need to consider the boolean onLoan from the a second class named car for them to be able to be applied, what I mean is that only cars which onLoan == false should be considered. I got to the base of them tried what it came to my mind about getting this solved but nothing for me seems to work at the moment some suggestions? Thank you!
/**
* Constructor for objects of class RentalCompany
*/
public void showAllCarsNotOnloan ()
{
for ( Car car:cars) {
if (cars.size()>0 ) {
int i = 0;
System.out.println(car.getDescription());
i++;
}
else if ( cars.size() < 0 ){
System.out.println ("Add cars first");
}
}
}
and the second method
public Car searchCar(String description)
{
for (Car car : cars) {
if (car.getDescription() == description) {
return car;
}
else {
System.out.println("This car is not listed. Retry!!");
}
}
return null;
}
The following will do the work:
The Car class:
public class Car {
private boolean onLoan;
// Other variables...
public boolean isOnLoan() {
return onLoan;
}
// Other methods....
}
Now, the showAllCarsNotOnloan method
public void showAllCarsNotOnloan() {
if (cars.size() == 0) {
System.out.println("Add cars first!");
return;
}
for (Car car : cars) {
if (!car.isOnLoan()) {
System.out.println(car.getDescription());
}
}
}
and the searchCar method
public Car searchCar(String description) {
for (Car car : cars) {
if (car.getDescription().equals(description)) {
return car;
}
}
System.out.println("This car not listed. Retry!!");
return null;
}

Categories

Resources