So I'm having this problem with adding an element to an ArrayList
I have a class Media with 3 fields and another class Mediatheque with 1 field(which is an ArrayList).
Let's say I have:
A Mediatheque media = new Mediatheque
An equals(Media m) method in class Media < (important method)
I need to write a method add(Media m) which:
If the media.contenu does contain an element equals to the Media m I want to add, I must NOT add it and increase the nbEx field of the element contained in media.contenu
-Else I can add it using the add method provided by the ArrayList ( This doesn't seem too hard)
So I tried to write a contains(Media) method which uses the equals(Media m) method I wrote for the Media class and then use the contains method in the add method.
My question is that how am I supposed to write the add method? < (The Question)
I must write this using ArrayList, it is a school assignment
Sorry about the long code and the bad English, I'm a complete noob.
Here is my Media class:
package Ex1;
public class Media {
private final String support; // Format: Book, CD, DVD,etc...
private final String titre; // Title
private int nbEx; // Number of copy
public Media(String titre, String support){
this.titre = titre;
this.support = support;
this.nbEx = 1;
}
public Media (){
titre = "";
support = "";
nbEx = 0;
}
public boolean equals(Media m){
boolean equality = false;
if (m instanceof Media){
equality = (this.titre.equals(m.titre) && this.support.equals(m.support));
}
return equality;
}
public Media(Media m){
this.titre = m.titre;
this.support = m.support;
}
}
And here is my Mediatheque class:
import java.util.ArrayList;
import static java.lang.System.out;
public class Mediatheque {
ArrayList<Media> contenu;
public Mediatheque(){
this.contenu = new ArrayList<Media>();
}
public Mediatheque(Mediatheque m){
this.contenu = m.contenu;
}
public boolean contains(Media m){
int i = 0;
boolean contain = this.contenu.get(i).equals(m);
for(i = 0; i<this.contenu.size(); i++){
if(contain)
break;
}
return contain;
}
public int indexOf(Media m){
boolean retVal = this.contenu.get(i).equals(m);
for(Media i : contenu){
if(contain)
break;
}
return i;
}
public void add(Media m){
if(this.contains(m)){
this.contenu.get(this.contenu.indexOf(m)).setNbEx(this.contenu.get(this.contenu.indexOf(m)).getNbEx()+m.getNbEx());
}else{
this.contenu.add(m);
}
}
My question is that how am I supposed to write the add method?
Sorry about the long code and the bad English, I'm a complete noob.
Thank you!
As stated by #NeplatnyUdaj in the comment of your question, the use of a Map would greatly improve your code. Instead of recording the number of medias inside the Media object, use a HashMap<Media, Integer> to store your data in this way:
new HashMap<Media, Integer> map = new HashMap<Media,Integer>();
if ( map.containsKey(key) ) {
map.put(key, (map.get(key) + 1));
} else {
map.put(key, 1);
}
Where key is the media. (m in your code)
When one overrides the equals() method, one is also supposed to override the hashCode() method. The equals() method takes an Object parameter. Here's how your Media class should look like:
// Media.java
public class Media
{
private final String support;
private final String title;
public Media(String title, String support)
{
this.title = title;
this.support = support;
}
public Media(Media media)
{
this(media.title, media.support);
}
#Override
public int hashCode()
{
return 31 * title.hashCode() + support.hashCode();
}
#Override
public boolean equals(Object object)
{
if (object instanceof Media)
{
Media media = (Media) object;
return media.title.equals(title) &&
media.support.equals(support);
}
return false;
}
}
Then use a HashMap to map the media with its number of copies. Here's how that's done:
// MediaMap.java
import java.util.HashMap;
import java.util.Map;
public class MediaMap
{
// Media to its Number of Copies mapping.
private Map<Media, Integer> mediaMap;
public MediaMap()
{
mediaMap = new HashMap<>();
}
public void add(Media media)
{
mediaMap.put(media, mediaMap.getOrDefault(media, 0) + 1);
}
public void removeOneMedia(Media media)
{
if (mediaMap.containsKey(media))
{
mediaMap.put(media, mediaMap.get(media) - 1);
}
}
// And so on...
}
Without overriding the hashCode() method in the Media class, the hash based collections won't work as expected.
You can also have a look at MultiSet data structure, and use that instead.
If you are to use ArrayList then here's how its done:
// Media.java
public class Media
{
private final String support;
private final String title;
private int numberOfCopies;
public Media(Media media)
{
this(media.title, media.support, media.numberOfCopies);
}
public Media(String title, String support, int numberOfCopies)
{
this.title = title;
this.support = support;
this.numberOfCopies = numberOfCopies;
}
#Override
public int hashCode()
{
return 31 * title.hashCode() + support.hashCode();
}
#Override
public boolean equals(Object object)
{
if (object instanceof Media)
{
Media media = (Media) object;
return media.title.equals(title) &&
media.support.equals(support);
}
return false;
}
public int getNumberOfCopies()
{
return numberOfCopies;
}
public void setNumberOfCopies(int numberOfCopies)
{
this.numberOfCopies = numberOfCopies;
}
}
And here's a MediaList class which uses ArrayList:
// MediaList.java
import java.util.ArrayList;
public class MediaList
{
private ArrayList<Media> mediaList;
public MediaList()
{
mediaList = new ArrayList<>();
}
public void add(Media media)
{
set(media, +1);
}
public void remove(Media media)
{
set(media, -1);
}
private void set(Media media, int change)
{
if (change == 0)
{
return;
}
int indexOfMedia = mediaList.indexOf(media);
if (indexOfMedia != -1)
{
Media m = mediaList.get(indexOfMedia);
m.setNumberOfCopies(m.getNumberOfCopies() + change);
if (change < 0 && m.getNumberOfCopies() <= 0)
{
mediaList.remove(media);
}
}
else if (change > 0)
{
mediaList.add(media);
}
}
// And so on...
}
I have refactored your classes a little bit. I also implemented an add method. I assumed that you want to add media to the mediatheque if it is not already in the list. If it is in the list you want to add the nbex to the nbex that the item in the list has, right?
As the others I would advise you to use a HashMap() for counting if you don't need the number for your media objects.
Media.class
public class Media {
private final String support; // Format: Book, CD, DVD,etc...
private final String titre; // Title
private int nbEx; // Number of copy
public Media(String titre, String support){
this.titre = titre;
this.support = support;
this.nbEx = 1;
}
public Media(Media m){
this(m.titre, m.support);
}
public Media (){
this("", "");
nbEx = 0;
}
public boolean equals(Media m){
if (m instanceof Media){
return (this.titre.equals(m.titre) && this.support.equals(m.support));
}
return false;
}
}
Mediatheque.class
public class Mediatheque {
ArrayList<Media> contenu;
public Mediatheque(){
this.contenu = new ArrayList<Media>();
}
public Mediatheque(Mediatheque m){
this.contenu = m.contenu;
}
public boolean contains(Media m){
for(Media media: this.contenu) {
if(media.equals(m) {
return true;
}
}
return false;
}
public int indexOf(Media m){
if(this.contenu.contains(m) {
return this.contenu.indexOf(m);
}
return -1;
}
public void add(Media m){
if(this.contains(m)) {
Media media = this.contenu.get(this.contenu.indexOf(m));
media.setNbex(media.getNbex() + m.getNbex());
} else {
this.contenu.add(m);
}
}
}
Hope this helps.
Related
I need to make a programm which is like a rally, theres 2 types of vehicles, motorcycle and cars, two types of motorcycle, with and without sidecar, the thing is that I need to verify if there is just a motorcycle in an array list, I mean, two wheels vehicle. That verification should be done in a method called esDe2Ruedas(), which is called by an abstract overrided method called check() that should be the one that verifies if a group of vehicles from an array are able to run in the rally, if its true all the elements of the array must be from the same type.
Here is the code
this is how the program arrays the vehicles
GrandPrix gp1 = new GrandPrix();
gp1.agregar(v1);
//gp1.mostrar(v1);
gp1.agregar(v2);
System.out.println(gp1.check());
GrandPrix gp2 = new GrandPrix();
gp2.agregar(vt1);
gp2.agregar(vt2);
gp2.agregar(m2);
System.out.println(gp2.check());
GrandPrix gp3 = new GrandPrix();
gp3.agregar(vt1);
gp3.agregar(vt2);
gp3.agregar(m1);
System.out.println(gp3.check());
GrandPrix gp4 = new GrandPrix();
gp4.agregar(m1);
gp4.agregar(m2);
System.out.println(gp4.check());
This is the class that is using
import java.util.ArrayList;
public class GrandPrix extends Rally{
ArrayList<Vehiculo> ve = new ArrayList<Vehiculo>();
public void agregar(Vehiculo v) {
ve.add(v);
}
public void agregar(Carro c) {
ve.add(c);
}
public void agregar(Moto m) {
ve.add(m);
}
#Override
boolean check() {// HERE I VERIFY IF THE VEHICLES ARE COMPATIBLE
return false;
}
}
This is the class where everything goes on
public class Vehiculo {
private String Nombre;
private double velocidad_max;
private int peso;
private int comb;
public Vehiculo() {
setNombre("Anónimo");
setVel(130);
setPeso(1000);
setComb(0);
}
public Vehiculo(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
}
double rendimiento() {
return velocidad_max/peso;
}
public boolean mejor(Vehiculo otroVehiculo) {
return rendimiento()>otroVehiculo.rendimiento();
}
public String toString() {
return getNombre()+"-> Velocidad máxima = "+getVel()+" km/h, Peso = "+getPeso()+" kg";
}
/**************************************
---------SET And GET Nombre------------
***************************************/
public String getNombre() {
return Nombre;
}
public void setNombre(String nuevoNombre) {
this.Nombre=nuevoNombre;
}
/**************************************
---------SET And GET velocidad_max------------
***************************************/
public double getVel() {
return velocidad_max;
}
public void setVel(double nuevaVel) {
this.velocidad_max=nuevaVel;
}
/**************************************
---------SET And GET peso------------
***************************************/
public double getPeso() {
return peso;
}
public void setPeso(int nuevoPeso) {
this.peso=nuevoPeso;
}
/**************************************
---------SET And GET comb------------
***************************************/
public int getComb() {
return comb;
}
public void setComb(int comb) {
this.comb = comb;
}
boolean esDe2Ruedas() {
return false;
}
}
This is the class of motorcycles, which is in theory the same as the car's class, without sidecar thing
public class Moto extends Vehiculo{
private boolean sidecar;
public Moto(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(false);
}
public Moto(String string, double d, int i, int j, boolean b) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(b);
esDe2Ruedas(false);
}
public String toString() {
String str = null;
if(isSidecar())
str =super.toString()+", Moto, con sidecar";
else
str =super.toString()+", Moto";
return str;
}
public boolean isSidecar() {
return sidecar;
}
public void setSidecar(boolean sidecar) {
this.sidecar = sidecar;
}
I guess what you presented is what is given. If you came up with the design it is ok, but I believe it could be improved. Anyway, I try to respond to what I believe was your question straight away.
Vehiculo is the super type of Moto (which can have a side car and becomes 3 wheeler).
Vehiculo has a method esDe2Ruedas, which returns false.
Moto inherits that method <-- this is wrong, it should override it and, depending on side car, return the expected boolean value.
In the check method you can now distinguish between Moto and "Moto with sidecar" by using that method.
I've created this method and I'm unsure why it says there's a missing return statement. do I need to change the print to a return? (it's the method at the very bottom) I'm a bit of a Java beginner so any help will be appreciated!
public class Book {
private String title;
private String author;
private int copies;
private boolean borrowed;
public Book( String inAuthor, String inTitle, int inNumberOfCopies ) {
this.author = inAuthor;
this.title = inAuthor;
this.copies = inNumberOfCopies;
}
public void borrowed() {
borrowed = true;
}
public void rented() {
borrowed = true;
}
public void returned() {
borrowed = false;
}
public boolean isBorrowed() {
return borrowed;
}
public String getAuthor() {
return this.author;
}
public static String getTitle() {
return getTitle();
}
public int getTotalCopies() {
return this.copies;
}
public int getAvailableCopies() {
}
public void withdrawCopy() {
int found = 0;
for (Book b : Library.getListOfBooks()) {
if (b.getTitle().equals(title)) {
if (found == 0) {
found = 1;
}
if (!b.isBorrowed()) {
b.borrowed=true;
found = 2;
break;
}
if (found == 0) {
System.out.println("Sorry, this book is not in our catalog.");
} else if (found == 1) {
System.out.println("Sorry, this book is already borrowed.");
} else if (found == 2) {
System.out.println("You successfully borrowed " + title);
}
}
}
}
public String returnCopy() {
boolean found = false;
for (Book book : Library.getListOfBooks()) {
if (getTitle().equals(title) && book.isBorrowed()) {
book.returned();
found = true;
}
if (found) {
System.out.println("you successfully returned " + title);
}
}
}
}
public String returnCopy()
String after public means that this method will return a String.
Your public String returnCopy() is currently not returning anything.
If you don't want to return anything, you can use void like this:
public void returnCopy(){
// code
}
Same issue with public int getAvailableCopies(), this is supposed to return an int but you are not returning anything.
Be careful:
this method:
public static String getTitle() {
return getTitle();
}
is a recursive method without a base condition. This will cause an error and force your application to crash.
You've defined the method as returning a String but you don't return a value anywhere in the method body. Simplest fix is probably to change the return type to void...
public void returnCopy() {...
}
All the above answer are pointing to the same issue, you have defined methods that are breaking the contract about what they return..
In you code you have as well something like this:
public int getAvailableCopies() {
}
so you are telling the compiler, you have a method with the name getAvailableCopies, it takes no params and return an integer.
BUT if you don't return anything, then you are contradicting your own method, your own contract, this is an enough reason for a compiler to complain...
Conclusion:
keep in mind the information that defines the method.
I want to modify the DifferenceListener in XMLUnit to ignore the attribute id while comparing XML files. I have tried to do it using the following.
import org.custommonkey.xmlunit.DifferenceListener;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.DifferenceConstants;
public class ignoreIDs implements DifferenceListener {
private static final int[] IGNORE_VALUES = new int[] {
DifferenceConstants.ATTR_VALUE.getId(),
};
private boolean isIgnoredDifference(Difference diff) {
int DiffId = diff.getId();
for (int value: IGNORE_VALUES) {
if (DiffId == value) return true;
}
return false;
}
public int differenceFound(Difference difference) {
if (isIgnoredDifference(difference)) return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
else return RETURN_ACCEPT_DIFFERENCE;
}
public void skippedComparison() {
}
}
But I am unable to understand how to enter only the id attribute in the IGNORE_VALUES array. Please help me out.
I have a set of objects. This objects calculate some numbers based on request parameters. Let's call them calculators. Each calculator has description where specified type of requests that this calculator the most suitable for.
For example,
Calculator1 : with this parameters : price > 10, gender = male, geo_id = 1, 2 or 3.
Calculator2 : with this parameters : price < 5, gender = male, geo_id = 1, 2.
For request : price = 11, gender = male, geo_id = 2 I should get calculator1 like the most suitable and then calculator2.
For request : price = 4, gender = male, geo_id = 2 I should get calculator2 and then calculator1.
For request : price = 3, gender = female, geo_id = 5 I should get only the second one.
Now I'm doing it with Lucene, but it's not really fit for this task. Can you recommend me some library or approach?
My suggestion would be to use a comparator. See a sketch of the classes below.
import java.util.HashMap;
import java.util.Map;
public abstract class Calculator {
public static Map<String, Integer> weights;
static {
weights = new HashMap<String, Integer>();
weights.put("price", 10);
weights.put("gender", 2);
weights.put("geo", 5);
}
public abstract int calculate(Map<String, Integer> request);
public abstract int fitnessFor(Map<String, Integer> request);
}
You can use the weights to adjust relative importance of the individual request parameters.
import java.util.Map;
public class Calculator1 extends Calculator {
public int calculate(Map<String, Integer> request) {
return -1;
}
#Override
public int fitnessFor(Map<String, Integer> request) {
int fitness = -1;
Integer price = request.get("price");
if (price == null)
return fitness;
if (price > 10)
fitness += weights.get("price");
return fitness;
}
public String toString() { return "Calculator1"; }
}
Calculator1 cares only about the pricey items.
import java.util.Map;
public class Calculator2 extends Calculator {
public int calculate(Map<String, Integer> request) {
return -1;
}
#Override
public int fitnessFor(Map<String, Integer> request) {
int fitness = -1;
Integer price = request.get("price");
if (price == null)
return fitness;
if (price < 5)
fitness += weights.get("price");
Integer gender = request.get("gender");
if (gender == null)
return fitness;
if (gender == 1)
fitness += weights.get("gender");
return fitness;
}
public String toString() { return "Calculator2"; }
}
Calculator2 cares about the less pricey items esp. if they are for gender 1.
The comparator just compares Calculators by their fitness relative to the request:
import java.util.Comparator;
import java.util.Map;
public class CalcComparator implements Comparator<Calculator> {
private Map<String, Integer> request;
public CalcComparator(Map<String, Integer> request) {
this.request = request;
}
#Override
public int compare(Calculator c1, Calculator c2) {
int c1Fitness = c1.fitnessFor(request);
int c2Fitness = c2.fitnessFor(request);
if (c1Fitness == c2Fitness)
return 0;
if (c1Fitness < c2Fitness)
return 1;
return -1;
}
}
Try it out with:
public class Main {
public static void main(String[] args) {
Map<String, Integer> request = new HashMap<String, Integer>();
request.put("price", 5);
request.put("gender", 1);
List<Calculator> calculators = new ArrayList<Calculator>();
calculators.add(new Calculator1());
calculators.add(new Calculator2());
Collections.sort(calculators, new CalcComparator(request));
System.out.println("For request: "+request);
for (Calculator c : calculators) {
System.out.println("\t"+c.toString() + "( fitness " + c.fitnessFor(request) + ")");
}
}
}
This is just a sketch to illustrate the idea. You will probably want to introduce an enum for the request parameters, maybe introduce a Request class, most likely change completely how fitness is computed, make some of the fields private and encapsulate them, etc.
The advantage is that you easily get an ordering of all the Calculators based on their fitness for the request.
Provided that I understood you correctly, I would suggest that you use the Specification design pattern which is used in cases like this. There's no need in such a fancy library like Lucene for such a simple task. The advantage of the Specification pattern is that it keeps all the filtering logic grouped and encapsulated. Your implementation may vary, but below is a simple example of what it could look like
public interface Specification<T> {
boolean isSatisfiedBy(T candidate);
Specification<T> and(Specification<T> specification);
Specification<T> or(Specification<T> specification);
Specification<T> not(Specification<T> specification);
}
public abstract class Calculator {
// ...
}
public class Calculator1 extends Calculator implements Specification<Request> {
public boolean isSatisfiedBy(Request request) {
// check if the request fits this calculator
}
}
public class Calculator2 extends Calculator implements Specification<Request> {
public boolean isSatisfiedBy(Request request) {
// check if the request fits this calculator
}
}
You can then have a collection or a pool of calculators such that
public class Calculators {
private final List<RequestSpecification> calculators;
public Calculator getOneSuitedFor(Request request) {
for (Calculator calculator : calculators) {
if (calculator.isSatisfiedBy(request)) {
return calculator;
}
}
return null;
}
}
And here how you would use it
Calculator calculator = Calculators.getOneSuitedFor(request);
Or, if needed, you can always go on and expand on it by making use of composition (see the reference link above) which allows for logic chaining and combining of different specifications depending on the context. This, however, would require a little bit different class design from that of above, but is more flexible
final Request request;
Specification<Calculator> price = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.supportsPrice(request.getPrice());
}
};
Specification<Calculator> gender = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.supportsGender(request.getGender());
}
};
Specification<Calculator> region = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.supportsRegion(request.getRegion());
}
};
Specification calcSpec = price.and(gender).and(region);
boolean isSatisfied = calcSpec.isSatisfiedBy(calculator);
Another interesting example is to use named specifications
Specification<Calculator> teenager = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.getAge() >= 13 && calculator.getAge() <= 19;
}
};
Specification<Calculator> male = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.getGender().equals("male");
}
};
Specification<Calculator> fromEurope = new Specification<>() {
public boolean isSatisfiedBy(Calculator calculator) {
return calculator.getRegion().equals("Europe");
}
};
Specification<Calculator> calcSpec = teenager.and(male).and(fromEurope);
boolean isSatisfied = calcSpec.isSatisfiedBy(calculator);
You could maybe try something like this:
public enum Calculator
{
CALC1
{
#Override
protected int matchCount( Map parameters )
{
// TODO count how many conditions match
return 0;
}
#Override
protected int calc( Map parameters )
{
// TODO
return 0;
}
},
CALC2
{
#Override
protected int matchCount( Map parameters )
{
// TODO count how many conditions match
return 0;
}
#Override
protected int calc( Map parameters )
{
// TODO
return 0;
}
};
protected abstract int matchCount( Map parameters );
protected abstract int calc( Map parameters );
public int doCalc( Map parameters )
{
Calculator mostSuited = null;
int maxCount = 0;
for ( Calculator calc : values() )
{
int matchCount = calc.matchCount( parameters );
if ( matchCount > maxCount )
{
mostSuited = calc;
}
}
return mostSuited.calc( parameters );
}
}
The way you would use the above is by invoking: int result = Calculator.doCalc( parameters )
Create a Calculator base class :
public static abstract class Calculator {
// This Contains the common score calculation methods.
public int getScore(int price, String gender, int geo_id) {
int score = 0;
if (gender.equalsIgnoreCase("male"))
score++;
if (getGeoIds().contains(geo_id))
score++;
return score;
}
public ArrayList<Integer> getGeoIds() {
// Fetching the common list of geo points to be compared.
ArrayList<Integer> lst = new ArrayList<Integer>();
lst.add(1);
lst.add(2);
return lst;
}
public abstract void doCalculation();
}
Then create your calculator classes by extending from this base.
public static class Calcualtor1 extends Calculator {
#Override
public int getScore(int price, String gender, int geo_id) {
// fetching score from common score calculation.
int score = super.getScore(price, gender, geo_id);
// Adding its own score logic.
if (price > 10)
score++;
return score;
}
#Override
public void doCalculation() {
// Do your actual work.
}
#Override
public ArrayList<Integer> getGeoIds() {
ArrayList<Integer> lst = super.getGeoIds();
// Adding the geo id to compare for this calculator.
lst.add(3);
return lst;
}
}
public static class Calcualtor2 extends Calculator {
#Override
public int getScore(int price, String gender, int geo_id) {
// fetching score from common score calculation.
int score = super.getScore(price, gender, geo_id);
// Adding its own score logic.
if (price < 5)
score++;
return score;
}
#Override
public void doCalculation() {
// Do your actual work.
}
}
Initialise values :
//To store the list of available calculators.
private static ArrayList<Class<? extends Calculator>> calculators;
static {
//Initializing the calculator list in static constructor.
calculators = new ArrayList<Class<? extends Calculator>>();
calculators.add(Calcualtor1.class);
calculators.add(Calcualtor2.class);
}
Actual processing :
public static void main(String[] args) {
int price = 10;
String gender = "male";
int geo_id = 2;
Calculator calculator = null;
int score = 0;
for (Class<? extends Calculator> calClass : calculators) {
Calculator cal = null;
try {
cal = calClass.newInstance();
} catch (Exception e) {
continue;
}
int calScore = cal.getScore(price, gender, geo_id);
if (calScore > score) {
calculator = cal;
score = calScore;
}
}
if (calculator != null) {
calculator.doCalculation();
}
}
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!