Selecting Random Method From Multiple Methods - java

I am trying to select a random method from the ones created inside the class. Is there a way to create an ArrayList and pass methods to it? I have attempted to do just that but I am getting an error when I try to add the method to the array.
public class Monkey{
private int energy;
String[] food = {"Meat", "Fish", "Bugs", "Grain"};
ArrayList<Activity> monkeyActivity = new ArrayList<>();
public Monkey(int energy) {
this.energy = energy;
}
public int getEnergy() {
System.out.println("Monkey energy level: " + energy);
return energy;
}
public void sound() {
System.out.println("Monkey: Oooo Oooo~!");
energy -= 3;
monkeyActivity.add(sound()); //I get an error message here when trying
//to add the method to the array
}
public void play(){
if (energy >= 8){
System.out.println("Monkey begins to play.");
energy -= 8;
}else {
System.out.println("Monkey does not have enough energy to play");
}
System.out.println("Energy remaining: " + energy);
}
public void eat(){
Random random = new Random();
int index = random.nextInt(food.length);
System.out.println("Monkey beings to eat " + food[index]);
energy += 5;
System.out.println("Energy remaining: " + energy);
}
public void sleep(){
System.out.println("Monkey is sleeping: Zzz...");
energy += 10;
System.out.println("Energy remaining: " + energy);
}
}
This is the separate class I have made for the generic Activity..
public class Activity {
private String sleep;
private String eat;
private String sound;
private String play;
public Activity(String sleep, String eat, String sound, String play) {
this.sleep = sleep;
this.eat = eat;
this.sound = sound;
this.play = play;
}
public String getSleep() {
return sleep;
}
public String getEat() {
return eat;
}
public String getSound() {
return sound;
}
public String getPlay() {
return play;
}
public void setSleep(String sleep) {
this.sleep = sleep;
}
public void setEat(String eat) {
this.eat = eat;
}
public void setSound(String sound) {
this.sound = sound;
}
public void setPlay(String play) {
this.play = play;
}
}

You are mixing up concepts.
technical issues:
return value clash
public void sound() {
// ...
monkeyActivity.add(sound());
The return value of your method sound() is void (which means no return value), but you try to add its (not existing) return value as element to the List. This is what your compiler complains about.
unintended recursion
public void sound() {
System.out.println("Monkey: Oooo Oooo~!");
energy -= 3;
monkeyActivity.add(sound());
In the last line you do a recursive call which means you call exactly the same method this code is in. If that happens unintended it almost ever results in a StackOverflowError.
writing classes without proper analysis
You have a class Activity.
But if you have a closer look this is not a single activity (as the classes name implies) but it is all possible activities.
As a result your collection monkeyActivity cannot hold single activities as elements.
Doing a wild guess I think what you wanted is more like this:
interface Activity{
void do();
}
public class Monkey{
private int energy;
String[] food = {"Meat", "Fish", "Bugs", "Grain"};
List<Activity> monkeyActivity = new ArrayList<>();
// ...
public void sound() {
monkeyActivity.add(new Activity(){
public void do(){
System.out.println("Monkey: Oooo Oooo~!");
energy -= 3;
}
});
}

You may store each method as Runnable, as any "action" is no-arg void method satisfying Runnable functional interface:
List<Runnable> actions = Arrays.asList(this::sound, this::play, this::eat, this::sleep);
to execute random method, just:
Random rnd = new Random();
actions.get(rnd.nextInt(actions.size())).run();

Related

Can you Implement a Singleton Pattern with a State Pattern

I have an application that I have been working on for a little while, I understand a little of Java.
The scope of the application is combine multiple design patterns in a way that allows reusability, which code can be edited without having to scroll through hundreds of lines of code.
I have implemented a true Singleton Player class.
I have also implemented a decorator weapon class.
I am not looking to add a state pattern for the player class, an example of this would be AliveState and DeadState. Something simple so I understand the workings of it all.
For the sake of this I will post the full PlayerSingleton class:
public class PlayerSingleton{
private static PlayerSingleton player;
Scanner scanner = new Scanner(System.in);
private String playerName;
private Integer playerHealth;
private Weapon weapon;
private PlayerSingleton(Weapon weapon, String pName, int pHealth) {
this.weapon = weapon;
playerName = pName;
playerHealth = pHealth;
}
public static Weapon chooseWeapon(String choice) {
switch (choice) {
case "MP5":
System.out.println("You have chosen MP5!");
return new MP5Weapon();
case "SNIPER":
System.out.println("You have chosen Sniper!");
return new SniperRifleWeapon();
case "SHOTGUN":
System.out.println("You have chosen Shotgun!");
return new ShotgunWeapon();
default:
System.out.println("No gun by that name found!");
return null;
}
}
public static PlayerSingleton getInstance(String choice, String name, int health) {
System.out.println("Choose Weapon to play the with: ");
Weapon weapon = PlayerSingleton.chooseWeapon(choice);
weapon.getDescription();
if (player == null) {
player = new PlayerSingleton(weapon, name, health);
}
return player;
}
public void getWeaponDamage(Weapon damage) {
System.out.println("Damage of weapon: " + weapon.damage());
}
public void attackState(double damage) {
damage = player.weapon.damage();
}
// #Override
// public void aliveState() {
// if(playerHealth >= 1){
//
// }
// }
// #Override
// public void deadState() {
// if(playerHealth ==0){
// System.out.println("You are dead");
// System.out.println("GameOver");
// }
// }
public void chosenWeapon() {
System.out.println("Player Info: " + playerName + " " + "Has: " + playerHealth + " health");
System.out.println(weapon.getDescription() + ":" + " base damage: " + weapon.damage());
}
public void addBasicAttachment(String attachment) {
switch (attachment) {
case "SIGHT":
weapon = new BasicSight(weapon);
break;
case "SILENCER":
weapon = new BasicSilencer(weapon);
break;
case "STOCK":
weapon = new BasicStock(weapon);
break;
default:
System.out.println("No Attachment found!");
}
}
I've tried to implement this with help of Head first design patterns (State) but using the Singleton Pattern on the player class means that I cannot call the object from another class.
public class DeadState implements PlayerState{
PlayerSingleton player;
public DeadState(PlayerSingleton player){
this.player = player;
}
#Override
public void deadState() {
System.out.println("You are Dead!");
}
#Override
public void aliveState() {
System.out.println("You are Dead!");
}
}
Above is a test on making a DeadState implementing from a PlayerState interface.
Is there any way to do this with separate classes using the state pattern with PlayerSingleton?
Seriously any help would be amazing!
Also if you could explain the answer so I understand better.
First of all about this sentence that you said:
using the Singleton Pattern on the player class means that I cannot call the object from another class.
Actually you can call the object from other classes, as long as you have access to the instance, and that's how state pattern works.
I took your classes and remove some code just for the sake of simplicity and explain better the solution, you can add back the parts of the code I removed if you use this solution:
I used the two states you have in your code, first this is the PlayerState interface, it has two methods, one for taking damage and other for respawning:
public interface PlayerState {
void respawn();
void takeDamage(int damage);
}
Then the implementation of Alive state has only implementation for the takeDamage method, which receives the amount of damage taken:
public class AliveState implements PlayerState {
private PlayerSingleton player;
public AliveState(PlayerSingleton player) {
this.player = player;
this.player.setHealth(PlayerSingleton.MAX_PLAYER_HEALTH);
}
#Override
public void takeDamage(int damage) {
System.out.println(String.format("Suffering %d damage!", damage));
player.setHealth(player.getHealth() - damage);
if (player.getHealth() <= 0) {
player.setLives(player.getLives() - 1);
player.setState(new DeadState(player));
}
}
#Override
public void respawn() {
System.out.println("Nothing to do, player is alive!");
}
}
Same for the implementation of the DeadState, which has only implementation for the respawn method, as long as the player has lives left:
public class DeadState implements PlayerState {
private PlayerSingleton player;
public DeadState(PlayerSingleton player) {
this.player = player;
}
#Override
public void takeDamage(int damage) {
System.out.println("Nothing to do, player is dead!");
}
#Override
public void respawn() {
if (player.getLives() > 0) {
System.out.println("respawning to start location!");
player.setState(new AliveState(player));
} else {
System.out.println("Game Over!");
}
}
}
And finally the PlayerSingleton class, which is assigned the state AliveState when the player is created, the takeDamage and respawn methods call the implementations in the current player's state, and if you noticed, the State implementations have a reference to the player's instance, so they can change the object state.
public class PlayerSingleton {
public static Integer MAX_PLAYER_HEALTH = 500;
public static Integer DEFAULT_PLAYER_LIVES = 2;
private static PlayerSingleton player;
private Integer health = MAX_PLAYER_HEALTH;
private int lives = DEFAULT_PLAYER_LIVES;
private PlayerState playerState;
private PlayerSingleton() {
setState(new AliveState(this));
}
public static PlayerSingleton getInstance() {
if (player == null) {
player = new PlayerSingleton();
}
return player;
}
public void sufferDamage(int damage) {
playerState.takeDamage(damage);
}
public void respawn(String location) {
playerState.respawn();
}
// Getters and Setters
}
I used the following main method to test:
public static void main(String[] args) {
PlayerSingleton playerSingleton = PlayerSingleton.getInstance();
playerSingleton.takeDamage(300);
playerSingleton.respawn();
playerSingleton.takeDamage(300);
playerSingleton.respawn();
playerSingleton.takeDamage(600);
playerSingleton.respawn();
}
And this was the output:
Suffering 300 damage!
Nothing to do, player is alive!
Suffering 300 damage!
Player is dead!
respawning to start location!
Suffering 600 damage!
Player is dead!
Game Over!

Why is it called the pull mechanism in the observer pattern? [duplicate]

At the moment I'm studying design patterns and I've come to a part where I'm confused whether the observer pattern makes use of the push mechanism or does it make use of the pull mechanism?
I've read different implementations of this and can't really establish which one is correct.
Also, I'd like to know three straight forward advantages of the push model towards the pull model.
I guess one of them is that the push model is less coupled then the pull model?
Observer Pattern in detail (with the focus on questions asked)
Definition : The Observer Pattern defines a one-to-many dependency between the objects so that when one object changes state, all of its dependents are notified and updated automatically
3 things to focus:
Observable object - The object being observed.
Observer objects - The objects that observe the observable object
Communication Mechanism - Pull or Push Mechanism
At the moment i'm studying design patterns and i've came to a part where i'm confused whether the observer pattern makes use of the push mechanism or does it makes use of the pull mechanism ?
Confusion might be because you are literary going by name - Pull or Push.
Please note that in both mechanisms, it is always the responsibility of Observable object to notify all the subscribed observers, but the difference lies whether [Push->]the observer get the exact data it wants or [Pull->] it get the data wrapped in some object (mostly Observable object) & it has to extract the required data from it.
Push -> Observer get the required data directly
Pull -> Observer get the data wrapped in an object and it needs to extract that.
I've read different implementations of this and can't really establish which one is correct.
It is not the question of correction here, actually both will work absolutely fine in any situation. It's just which is best suited to a particular scenario/situation which can be easily analysed if we see following details for both the mechanism.
Also i'd like to know three straight forward advantages of the push model towards the pull model. I guess one of them is that the push model is less coupled then the pull model ?
I may not be able to provide 3 advantages, but let me try if I can give you a clear picture of where to use what by using use-case examples:
Push Mechanism
This is purely the Observable's responsibility, Observer just need to make sure they have put required code in their update methods.
Advantages
The main advantage of the 'push' model is lower coupling between the observer and the subject.
Observable & Observer both are interfaces/abstract classes which is actually a design principle - Program to interface or supertypes
Disadvantage
Less flexibility : As Observable needs to send the required data to the Observer and it would become messy if we have say 1000 observers and most of them require different types of data.
Use-Case
It should be used when there are max 2-3 different types of Observers (different types means observer require different data) or all observers require same type of data.
Like token systems in a bank
In this all observers (different LEDs) just need one notification the list of updated waiting token numbers, so may better be implemented in this way as compared to Pull Mechanism.
Pull Mechanism
In pull mechanism as well, it is the Observable's responsibility to notify all observer that something has been changed, but this time Observable shares the whole object which has the changes, some observers might not require the complete object, so Observers just need extract the required details from that complete project in their update methods.
Advantages
The advantage of this is more flexibility.
Each observer can decide for itself what to query, without relying on the subject to send the correct (only required) information.
Disadvantage
The observers would have to know things about the subject in order to query the right information from the shared complete object.
Use-Case
It should be used when there are more than 2-3 different types of Observers (different types means observer require different data)
Like publishing of FX Rates by any foreign exchange rates provider for different investment banks
In this Some banks just deals with only INR, some others only GBP etc. so it should be implemented using Pull mechanism as compared to Push mechanism.
References
Head-First book for design Patterns
https://softwareengineering.stackexchange.com/questions/253398/the-observer-pattern-using-the-pulling-mechanism?newreg=999c28a6a1f6499783fbe56eb97fa8ec
https://dzone.com/articles/observer-pattern
This is an example code that uses the "PULL" mode as explained above Observers could get different types of data (not implemented in this case).
import java.io.*;
import java.util.*;
interface Observer{
public void update();
}
interface Observable {
public void notifyAll() throws Exception;
public void notify(Observer o) throws Exception;
}
class Suscriber implements Observer {
String id;
Subject subject;
boolean registered = false;
Double data = 0.0;
public Suscriber(String id,Subject sub){
this.id = id;
subject = sub;
subject.register(this);
registered = true;
}
public void update() {
if(registered){
data = subject.getData();
}
display();
}
void display(){
System.out.println("Suscriber:" + id + " updated");
System.out.println("Current DATA: " + data);
}
}
class Subject implements Observable{
private List<Observer> observers = new ArrayList<Observer>();
private Double data = 0.0;
public void register(Observer o){
observers.add(o);
}
public void unregister(Observer o){
int i = observers.indexOf(o);
observers.remove(i);
}
public void notify(Observer o) throws Exception{
o.update();
}
public void notifyAll() throws Exception {
for(Observer o:observers)
this.notify(o);
}
public void computeMetrics(){
try{
long bunch = System.currentTimeMillis()/2;
data = data + new Double(bunch);
this.notifyAll();
}catch(Exception ex){
ex.printStackTrace();
}
}
public Double getData() {
return this.data;
}
}
class ObserverTestDrive {
public static void main (String[] args) {
Subject subject = new Subject();
long transmission = 10000;
Suscriber norths = new Suscriber("NorthStation",subject);
Suscriber wests = new Suscriber("WestStation",subject);
Suscriber souths = new Suscriber("SouthStation",subject);
for(int i=0;i<transmission;i++)
subject.computeMetrics();
}
}
Here are two examples (one using push and other using pull) from Head First Design Patterns.
Push:
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
public interface Observer {
public void update(float temp, float humidity, float pressure);
}
import java.util.*;
public class WeatherData implements Subject {
private ArrayList<Observer> observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData() {
observers = new ArrayList<Observer>();
}
public void registerObserver(Observer o) {
observers.add(o);
}
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
public void notifyObservers() {
for (int i = 0; i < observers.size(); i++) {
Observer observer = (Observer)observers.get(i);
observer.update(temperature, humidity, pressure);
}
}
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
notifyObservers();
}
public float getTemperature() {
return temperature;
}
public float getHumidity() {
return humidity;
}
public float getPressure() {
return pressure;
}
}
public class CurrentConditionsDisplay implements Observer {
private float temperature;
private float humidity;
private WeatherData weatherData;
public CurrentConditionsDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
display();
}
public void display() {
System.out.println("Current conditions: " + temperature
+ "F degrees and " + humidity + "% humidity");
}
}
public class StatisticsDisplay implements Observer {
private float maxTemp = 0.0f;
private float minTemp = 200;
private float tempSum= 0.0f;
private int numReadings;
private WeatherData weatherData;
public StatisticsDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update(float temp, float humidity, float pressure) {
tempSum += temp;
numReadings++;
if (temp > maxTemp) {
maxTemp = temp;
}
if (temp < minTemp) {
minTemp = temp;
}
display();
}
public void display() {
System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings)
+ "/" + maxTemp + "/" + minTemp);
}
}
public class ForecastDisplay implements Observer, DisplayElement {
private float currentPressure = 29.92f;
private float lastPressure;
private WeatherData weatherData;
public ForecastDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update(float temp, float humidity, float pressure) {
lastPressure = currentPressure;
currentPressure = pressure;
display();
}
public void display() {
System.out.print("Forecast: ");
if (currentPressure > lastPressure) {
System.out.println("Improving weather on the way!");
} else if (currentPressure == lastPressure) {
System.out.println("More of the same");
} else if (currentPressure < lastPressure) {
System.out.println("Watch out for cooler, rainy weather");
}
}
}
public class WeatherStation {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay =
new CurrentConditionsDisplay(weatherData);
StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);
ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(82, 70, 29.2f);
weatherData.setMeasurements(78, 90, 29.2f);
}
}
Pull:
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
public interface Observer {
public void update();
}
import java.util.*;
public class WeatherData implements Subject {
private ArrayList<Observer> observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData() {
observers = new ArrayList<Observer>();
}
public void registerObserver(Observer o) {
observers.add(o);
}
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
notifyObservers();
}
public float getTemperature() {
return temperature;
}
public float getHumidity() {
return humidity;
}
public float getPressure() {
return pressure;
}
}
public class CurrentConditionsDisplay implements Observer {
private float temperature;
private float humidity;
private WeatherData weatherData;
public CurrentConditionsDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update() {
this.temperature = weatherData.getTemperature();
this.humidity = weatherData.getHumidity();
System.out.println("Current conditions: " + temperature
+ "F degrees and " + humidity + "% humidity");
}
}
public class StatisticsDisplay implements Observer {
private float maxTemp = 0.0f;
private float minTemp = 200;
private float tempSum= 0.0f;
private int numReadings;
private WeatherData weatherData;
public StatisticsDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update() {
float temp = weatherData.getTemperature();
tempSum += temp;
numReadings++;
if (temp > maxTemp) {
maxTemp = temp;
}
if (temp < minTemp) {
minTemp = temp;
}
System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings)
+ "/" + maxTemp + "/" + minTemp);
}
}
public class ForecastDisplay implements Observer {
private float currentPressure = 29.92f;
private float lastPressure;
private WeatherData weatherData;
public ForecastDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update() {
lastPressure = currentPressure;
currentPressure = weatherData.getPressure();
System.out.print("Forecast: ");
if (currentPressure > lastPressure) {
System.out.println("Improving weather on the way!");
} else if (currentPressure == lastPressure) {
System.out.println("More of the same");
} else if (currentPressure < lastPressure) {
System.out.println("Watch out for cooler, rainy weather");
}
}
}
public class WeatherStation {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay =
new CurrentConditionsDisplay(weatherData);
StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);
ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(82, 70, 29.2f);
weatherData.setMeasurements(78, 90, 29.2f);
}
}
The difference being, in case of Push, the Subject not only let the observer know that he has new data, he also send the data to Observer (regardless of whether the Observer asked for it or not).
For example, let's check the update method of StatisticsDisplay in push:
public void update(float temp, float humidity, float pressure) {
tempSum += temp;
numReadings++;
if (temp > maxTemp) {
maxTemp = temp;
}
if (temp < minTemp) {
minTemp = temp;
}
display();
}
In case of Pull, the Subject not only let the observer know that he has new data. The Observer use the getter methods on the Subject to pull the values it needs.
For example, let's check the update method of StatisticsDisplay in pull:
public void update() {
float temp = weatherData.getTemperature();
tempSum += temp;
numReadings++;
if (temp > maxTemp) {
maxTemp = temp;
}
if (temp < minTemp) {
minTemp = temp;
}
System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings)
+ "/" + maxTemp + "/" + minTemp);
}
You might have also noticed that in case of pull, update method does not have any arguments.
The observer pattern uses push since the observable object push notifications to its subscribers.
Push vs Pull (in web mostly):
Push - the server sends(push) notifications to clients, this means it needs keep tracking on their address (URI) or in the more general case their reference.
Pull - the client is responsible for requesting fresh data from the server.
The pattern is not only for Web and is used all over, for example in desktop applications.

Player class winning percentage java

I am trying to create a method for " winning percentage " in a player class. I know I need to incorporate total wins divided by total games played, but the code is meant to be simple so I cannot use complex code. (beginner project in computer science) Any useful feedback would be great as I have spent multiple days attempting this and getting no where. By the way, ties count as half a win.
Update: Implemented the getters into the getWinningPercentage method. Also calculated everything inside the getWinningPercentage and removed the setWinningPercentage considering it was useless code. Results were as follows:
Bob
5 wins, 1 losses, 2 ties
Winning percentage = 0.75
public class Player
{
private int numWins = 0;
private int numTies = 0;
private int numLosses = 0;
private String name;
public void setWins(int w)
{
numWins = w;
}
public int getWins()
{
return numWins;
}
public void setTies(int t)
{
numTies = t;
}
public int getTies()
{
return numTies;
}
public void setLosses(int L)
{
numLosses = L;
}
public int getLosses()
{
return numLosses;
}
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
public void incrementWins()
}
numWins++;
}
public void incrementTies()
{
numTies++;
}
public void incrementLosses()
{
numLosses++;
}
public double getWinningPercentage()
{
double totalGames = getWins() + getTies() + getLosses();
double totalWins = getWins() + (getTies() / 2.0);
double winningPercentage = (totalWins / totalGames);
return winningPercentage;
}
}
The winning percentage should be a calculated property, not a field, and not have a setter method. Instead there should only be a "getter" (public double getWinningPercentage()) method and you should calculate and return this value from within the method itself from the other fields that your class already has.
We should leave it up to you to create this method and formula yourself.

creating a method that can remove items from an arraylist and add them to another arraylist (under certain conditions)

Hello i am writing a program that creates a method that can remove items from an arraylist and add them to another ArrayList (under certain conditions). This is the method I am supposed to create: 
A method called giveAwayFish() which represents a person
returning his fish to the pond and/or giving them away to another fisher.
It will go through all of this person's fish ( the one giving the fish away) and see if the other fisher ( the one who will be receiving the fish) is willing to keep any. If the other fisher wants any, they are to be given to that fisher. If the fisher is unwilling to keep the fish, then these fish must be returned to the pond.
I tried writing out this method about a hundred times and I can not for the life of me figure out what to do. I was able to remove all the fish from the persons array but I do not know how to add them back. This is what I need help with.
Here is my code if it helps:
import java.util.*;
public class Fisher
{
private String name;
private Fish [] fishCaught;
private int numFishCaught;
private int keepSize;
public static int LIMIT = 10;
public String getName()
{
return this.name;
}
public int getNumFishCaught()
{
return this.numFishCaught;
}
public int getKeepSize()
{
return this.keepSize;
}
public Fisher(String n, int k)
{
name = n;
keepSize = k;
}
public String toString()
{
return(this.name + " with " + this.numFishCaught + " fish as follows:");
}
private ArrayList<Fish> fishesCaught = new ArrayList<Fish>();
public void keep(Fish fish)
{
if(this.numFishCaught < LIMIT)
{
fishesCaught.add(fish);
numFishCaught++;
}
}
public boolean likes(Fish fish)
{
if(fish.size >= this.keepSize && fish.species != "Sunfish")
{
return true;
}
else
{
return false;
}
}
public void listFish()
{
System.out.println(this.toString());
for(Fish fish : fishesCaught)
{
System.out.println(fish.toString());
}
}
public void goFishingIn(Pond pond)
{
Fish fish = pond.catchAFish();
if(likes(fish))
{
this.keep(fish);
}
else
{
pond.add(fish);
}
}
public void giveAwayFish(Fisher fisher, Pond pond)
{
Fish fish = fishesCaught;
if(fisher.likes(fish))
{
fishesCaught.clear();
this.numFishCaught = 0;
}
}
}
Biggest problem here is (yes, there are lots of other problems), in your giveAwayFish(), you wrote
Fish fish = fishesCaught;
However fishesCaught is a List<Fish>. That can't even compile.
I believe what you want to do is something like (in psuedo code):
for (Fish fish : fishesCaught) {
if (fisher.like(fish)) {
fisher.keep(fish);
} else {
pond.addFish(fish);
}
}
fishesCaught.clear();

Add weapons to inventory

I am trying to add weapons to a player inventory. It's kind of hard to explain, so I'll try my best. What I have are a class for each weapon, a class for Combat, and a class for the Player. I am trying to get it to where when the Random number equals a certain number, it will add a weapon to the player inventory. I will put my code Below.
Combat Class:
public class Combat {
M4 m4 = new M4();
M16 m16 = new M16();
M9 m9 = new M9();
Glock glock = new Glock();
SCAR Scar = new SCAR();
Player player = new Player();
final int chanceOfDrop = 3;
static boolean[] hasWeapon = {false, true};
public static int ranNumberGen(int chanceOfDrop) {
return (int) (Math.random()*5);
}
private void enemyDead() {
boolean canDrop = false;
if(ranNumberGen(chanceOfDrop)==0){
canDrop = true;
}
if(canDrop == true){
if(ranNumberGen(0) == 1) {
Player.addInvetory(m4.weaponName(wepName), m4.weaponAmmo(wepAmmo)); //Issues here. wepName & wepAmmo cannot be resolved into variable
//Should I just delete the line?
//Trying to get it to add the weapon M4 to the player inventory.
//Maybe use an ArrayList? If so I need a couple pointers on how to implement this.
}
}
}
}
M4 Class:
public class M4 implements Armory {
//Weapon classes are practically identical except for differences in the name wepDamage and wepAmmo.
public Integer weaponAmmo(int wepAmmo) {
wepAmmo = 10;
return wepAmmo;
}
public Integer weaponDamage(int wepDamage) {
wepDamage = 5;
return wepDamage;
}
public String weaponName(String wepName) {
wepName = "M4";
return wepName;
}
Player Class:
public class Player {
public static int health = 100;
//Player Class.
public static void addInvetory(String wepName, int wepAmmo) {
Player.addInvetory(wepName, wepAmmo);
}
public static void removeInventory(String wepName, int wepAmmo) {
Player.addInvetory(wepName, wepAmmo);
}
public static void removeAll(String wepName, int wepAmmo) {
Player.removeAll(wepName, wepAmmo);
}
Interface:
public interface Armory {
//Interface implemented by all of the weapons classes.
public Integer weaponAmmo(int wepAmmo);
public Integer weaponDamage(int wepDamage);
public String weaponName(String wepName);
Hope you can help!
class Weapon {
private final String name;
private final int damage;
private final int ammo;
public Weapon(final String name,final int damage,final int ammo) {
this.name = name;
this.damage = damage;
this.ammo = ammo;
}
public Weapon clone() {
return new Weapon(this.name,this.damage,this.ammo);
}
public String getName() {
return this.name;
}
public int getAmmo() {
return this.ammo;
}
public int getDamage() {
return this.damage;
}
}
class WeaponFactory {
static WeaponFactory factory;
public static WeaponFactory getWeaponFactory() {
if(factory == null) {
factory = new WeaponFactory();
}
return factory;
}
private ArrayList<Weapon> weapons = new ArrayList<Weapon>();
private Random random;
private WeaponFactory() {
//TODO: Fix Ammo and Damage
weapons.add(new Weapon("M4",0,0));
weapons.add(new Weapon("M16",0,0));
weapons.add(new Weapon("M9",0,0));
weapons.add(new Weapon("Glock",0,0));
weapons.add(new Weapon("SCAR",0,0));
}
public Weapon getWeapon() {
int w = random.nextInt(weapons.length);
return weapons.get(w).clone();
}
}
class Combat {
...
private void enemyDead() {
if(ranNumberGen(chanceOfDrop)==0){
Player.addInventory(WeaponFactory.getWeaponFactory().getWeapon());
}
}
}
You can use an array of Armory and the generate a random number from 0 to the size of the array as an index to the array to decide which weapon to add.
Okay dude, since your question about creating a programming language was closed, I'm answering it through here:
I think that your idea is great! Don't give up on it, yet don't get too excited. I would try all the options that you have heard of(interpreted route AND the Compiled route). If you can get either of those to work, then you may proceed to go into further detail with the language creation. It's going to take a while though. Be patient!

Categories