Massive StackOverflowError from GSON toJson - java

So I am trying to use GSON to convert a class into a JSON file with the toJson() function and every time the code gets called there is a massive 1000+ line StackOverflowError. This is the error: http://pastebin.com/dBhYUFva
And here is the class I am doing gson.toJson() on:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import mc.kwit.arena.players.ArenaPlayer;
import mc.kwit.arena.util.PlayerUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Zach on 8/3/16.
*/
public class Match {
List<ArenaPlayer> arenaPlayers = new ArrayList<ArenaPlayer>();
String[] uuidArray = null;
Player winner;
String matchId = "123456";
int killLimit = 5;
int timeLimit = -1;
public Match() {
}
public Match(List<ArenaPlayer> arenaPlayerList, String id, int seconds, int kills) {
this.arenaPlayers = arenaPlayerList;
this.matchId = id;
this.timeLimit = seconds;
this.killLimit = kills;
}
public Match(String[] players, String id, int seconds, int kills) {
this.uuidArray = players;
this.matchId = id;
this.timeLimit = seconds;
this.killLimit = kills;
}
public void start() {
//Create our ArenaPlayer objects
this.arenaPlayers = PlayerUtil.uuidToArenaPlayerList(uuidArray);
Bukkit.getLogger().info("Match \" " + this.matchId + "\" has been started!");
//Whitelist all participants
for(ArenaPlayer p : arenaPlayers) {
KwitArena.pc.addArenaPlayer(p.getPlayer());
p.getPlayer().setWhitelisted(true);
Bukkit.getLogger().info(p.getName() + " has been whitelisted!");
p.setMatch(this);
}
}
public void finish() throws Exception {
//Remove all players from whitelist and game
for(ArenaPlayer p : arenaPlayers) {
p.getPlayer().setWhitelisted(false);
if(p.isWinner()){
p.kick(ChatColor.GREEN + "You have won the game!");
this.winner = p.getPlayer();
} else {
p.kick(ChatColor.RED + winner.getName() + "has won the game :(");
}
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String stats = gson.toJson(this);
KwitArena.postStats(stats);
//Remove this arena instance from the plugin
KwitArena.match = null;
}
public String getId(){
return(this.matchId);
}
public void setWinner(ArenaPlayer p) {
this.winner = p.getPlayer();
}
}
ArenaPlayer.class :
import mc.kwit.arena.Match;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
/**
* Created by Zach on 7/31/16.
*/
public class ArenaPlayer {
ArenaPlayer ap;
Player player;
OfflinePlayer offlinePlayer;
int kills = 0;
int deaths = 0;
boolean isInGame = false;
Match match = null;
boolean isWinner = false;
public ArenaPlayer(Player player){
this.player = player;
}
public ArenaPlayer(Player player, boolean playing, int numKills, int numDeaths) {
this.player = player;
kills = numKills;
deaths = numDeaths;
isInGame = playing;
}
//Getters
public String getMatchId() { return(this.match.getId());}
public int getKills() { return(this.kills);}
public int getDeaths() { return(this.deaths);}
public Match getMatch() { return(this.match);}
public Player getPlayer() { return(this.player);}
public String getName() { return(player.getName());}
public OfflinePlayer getOfflinePlayer() { return(this.offlinePlayer);}
//Setters
public void setMatch(Match match) { this.match = match;}
public void setIsWinner(boolean b) { this.isWinner = b;}
public void setOfflinePlayer(OfflinePlayer off) { this.offlinePlayer = off; }
//Extras
public void addDeath() { this.deaths++;}
public void addKill() { this.kills++;}
public boolean isPlaying() { return(this.isInGame);}
public boolean isWinner() { return(this.isWinner);}
public void kick(String message) { player.kickPlayer(message);}
}
I'm not really sure where to even begin in the stack trace, anyone have some pointers?

I think the problem is that Match has an ArenaPlayer field, and ArenaPlayer has a Match field, which if the two instances reference each other causes Gson to go into an infinite loop due to its implementation.
You'll have to detangle your classes, your instances, or use a different library, or exclude certain fields from serialization - see Gson doc.
BTW, 1000 is the default call stack depth - if you see this many lines in the stack, you've probably hit an infinite recursion.

Related

update object in hashmap by java 8 lambda

I created an item named player as follows:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class player implements Comparable <player> {
int PlayerId ;
String name ;
double salary;
public player(int PlayerId) {
this.PlayerId = PlayerId;
}
public void setPlayerId(int PlayerId) {
this.PlayerId = PlayerId;
}
public void setName(String name) {
this.name = name;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getID() {
return PlayerId;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
#Override
public int hashCode() {
int key = 2;
return key=2*key+PlayerId;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final player other = (player) obj;
if (this.PlayerId != other.PlayerId) {
return false;
}
return true;
}
#Override
public String toString(){
return hashCode()+" "+getID() +" "+getName()+" "+getSalary();
}
// generic method StoreplayerDetails
public <T> void StoreplayerDetails( HashMap<Integer,T> inputMap ) {
// save elements into text file
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream("OutPut.txt"));
for(T element : inputMap.values())
pw.println(element);
pw.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
} finally {
pw.close();
}
}
#Override
public int compareTo(player other) {
if(this.salary>other.salary)
return 1;
else
if(this.salary<other.salary)
return -1;
return 0;
}
public interface Update {
public <T> void updateSalaries( HashMap<Integer,player> inputMap);
}
}
create an interface named update in the player class ,create a generic method named updateSalaries in the interface that takes a HashMap as input and returns a Queue of player objects after updating the salaries of players by adding 500 to each one's salary .
in the mainprogram class implement the method updatesalaries as a lamdba expression .in the mainprogram class,print the elements in the returned queue .
I tried it as follows but it did not work out:
#Override
public <T> void updateSalaries(HashMap<Integer, player> map) {
map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;
System.out.println("new map"+map);
}
This is the full code in the main class
import java.util.HashMap;
import player.player.Update;
public class MainProgram implements Update{
public static void main(String[] args) {
HashMap< Integer,player> Keys = new HashMap<>();
player p1 =new player(1);
p1.setName("Ali");
p1.setSalary(5000);
player p2 =new player(2);
p2.setName("Sayed");
p2.setSalary(7000);
player p3 =new player(3);
p3.setName("soha");
p3.setSalary(3000);
Keys.put(1, p1);
Keys.put(2, p2);
Keys.put(3, p3);
// p1.StoreplayerDetails(Keys);
MainProgram m = new MainProgram();
m.updateSalaries(Keys);
}
#Override
public <T> void updateSalaries(HashMap<Integer, player> map) {
map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;
System.out.println("new map"+map);
}
}
Is there any help in solving this?
In your code snippet you have the following line of code:
map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;
Let's take this apart piece by piece:
map.replaceAll This method lets you replace all the values in a map. I believe you want to manipulate the values that are already there, instead.
(k,player.getSalary()) This is where you name the variables that the lambda will dump values into. You aren't supposed to supply numbers here, you are supposed to be receiving numbers. You likely want (k, p), where k will be set to the key (an Integer) and p will be set to the value (a player).
player.getSalary()+500 This returns an int. The replaceAll method requires that you return the value type, which in this case is player.
You forgot to include a close parenthesis at the end.
I believe you want to use this line of code instead, which mitigates all of the above errors:
map.forEach((k, p) -> p.setSalary(p.getSalary() + 500));

Printing job status only once based on the status

I'm new to Java and I would like to ask a more theoretical question. I'm trying to add a new feature on a working program which is written in Java. The purpose of the program is to run multiple jobs in the background and check their status. The status could be "Ready", "Waiting", "Running", "Stopped", "Done". I would like to create a method which will print some information to the output, which is based on the status of the running jobs. The rules for the printing:
For the first time of checking the job, it should print: "Started: " + job.getName().
If job is stopped it should print "Failed: " + job.getName().
If job is done running it should print "Done: " + job.getName().
In the job class I declared two variables:
private boolean startDisplay = false;
private boolean endDisplay = false;
I did a loop through all jobs and check their status and print the proper message for each case. Also, I updated the variables to be true. But the problem is it prints the same string over and over. So I made those variables static:
private static boolean startDisplay = false;
private static boolean endDisplay = false;
But, in this way it will print start and end for only one job (and not for the others).
How can I print every message only once? I thought of using the hashmap but it does not feel the right OOP way.
From What I guess you need a POJO class something like following :
package com.stackoverflow;
public class Job {
private String jobName;
private boolean startDisplay = false;
private boolean endDisplay = false;
private boolean doneDisplay = false;
public Job(String jobName) {
this.jobName = jobName;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public boolean isStartDisplay() {
return startDisplay;
}
public void setStartDisplay(boolean startDisplay) {
this.startDisplay = startDisplay;
}
public boolean isEndDisplay() {
return endDisplay;
}
public void setEndDisplay(boolean endDisplay) {
this.endDisplay = endDisplay;
}
public boolean isDoneDisplay() {
return doneDisplay;
}
public void setDoneDisplay(boolean doneDisplay) {
this.doneDisplay = doneDisplay;
}
}
And a Class to manage your POJO :
package com.stackoverflow;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Job> jobs = new ArrayList<>();
for (int i = 0; i < 5; i++) {
jobs.add(new Job("Job" + (i+1)));
}
String prompt = "";
while (!prompt.equals("q")) {
Scanner scanner = new Scanner(System.in);
prompt = scanner.nextLine();
if (prompt.equals("q"))
System.out.println("Bye");
if (prompt.equals("1")) {
System.out.println("Checking Job1 " + jobs.get(0).getJobName());
System.out.println("Started: " + jobs.get(0).isStartDisplay());
System.out.println("Done: " + jobs.get(0).isDoneDisplay());
System.out.println("Finished: " + jobs.get(0).isEndDisplay());
System.out.println("Changing State of the job....");
jobs.get(0).setStartDisplay(true);
}
}
}
}
Try to declare the boolean variables with the volatile keyword. Otherwise the main thread will not reliably see the changes made by the other threads.

Java ArrayList.contains() & add() method

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.

Java dynamic class casting using visitor pattern or reflection? Missing steps or bad implementation?

I am creating objects that will have properties in common based on user input and then passing the objects to a common method that will take appropriate action based on the object type.
I've been able to sort of get this working using a visitor class but it is not quite what I want. I want to be able to determine the object type in the common method and then access the methods associated with that object. I am not sure if I am close and just missing something or if I just have a bad implementation... or both =).
Here is my (complete) code:
package com.theory.bang.big;
public interface Particle
{
public enum ParticleType {
QUARK,
LEPTON
}
int processParticle(Particle p);
}
package com.theory.bang.big;
import java.util.ArrayList;
public class Quark implements Particle
{
ArrayList<String> flavorList;
/**
* Constructor for objects of class Quark
*/
public Quark()
{
flavorList = new ArrayList<String>();
flavorList.add("up");
flavorList.add("down");
flavorList.add("charm");
flavorList.add("strange");
flavorList.add("top");
flavorList.add("bottom");
}
public ArrayList<String> getFlavors()
{
return flavorList;
}
#Override
public int processParticle(Particle p)
{
System.out.println("In processParticle(Quark)");
// Never called?
return 0;
}
}
package com.theory.bang.big;
import java.util.ArrayList;
public class Lepton implements Particle
{
ArrayList<String> typeList;
/**
* Constructor for objects of class Lepton
*/
public Lepton()
{
typeList = new ArrayList<String>();
typeList.add("electron");
typeList.add("electron neutrino");
typeList.add("muon");
typeList.add("muon neutrino");
typeList.add("tau");
typeList.add("tau neutrino");
}
public ArrayList<String> getTypes()
{
return typeList;
}
#Override
public int processParticle(Particle p)
{
System.out.println("In processParticle(Lepton)");
return 0;
}
}
package com.theory.bang.big;
import java.lang.reflect.*;
class ParticleVisitor
{
public void visit( Quark q )
{
System.out.println("Quark:[" + q.getFlavors() + "]");
}
public void visit( Lepton l )
{
System.out.println("Lepton:[" + l.getTypes() + "]");
}
public void visit( Object e ) throws Exception
{
Method m = getClass().getMethod
( "visit", new Class[]{e.getClass()} );
m.invoke( this, new Object[]{e} );
}
}
package com.theory.bang.big;
import java.io.File;
public class Accelerate implements Particle
{
/**
* Constructor for objects of class Accelerate
*/
public Accelerate(Particle p)
{
processParticle(p);
}
//#Override
public int processParticle(Particle p)
{
try {
ParticleVisitor pv = new ParticleVisitor();
pv.visit(p);
} catch (Exception x) {
System.out.println(x);
}
return 0;
}
}
package com.theory.bang.big;
import java.io.File;
import java.util.Scanner;
public class Physics
{
public static void main(String[] args)
{
boolean done = false;
while (!done) {
System.out.print("Enter the particle [Quark or Lepton]: ");
Scanner in = new Scanner(System.in);
String input = in.next();
if (input.equals("Quark")) {
System.out.println("Quark");
Quark q = new Quark();
new Accelerate(q);
} else if (input.equals("Lepton")) {
System.out.println("Lepton");
Lepton l = new Lepton();
new Accelerate(l);
} else {
done = true;
}
}
}
}
Currently I can print the Quark flavors and Lepton types via the visit methods but what I need is to be able to execute (to be implemented) getter/setters (e.g. getSpin(), setSpin(double s)) for the respective objects in Accelerate().
What am I missing? Or is there a better way to implement this?
Thank you very much for your time.
-Walter
For your concrete example, you can throw away all that stuff and use overloading by parameter types:
public class Physics {
public static void processParticle( Quark q ) {
System.out.println("Quark:[" + q.getFlavors() + "]");
}
public static void processParticle( Lepton l ) {
System.out.println("Lepton:[" + l.getTypes() + "]");
}
public static void main(String[] args) {
boolean done = false;
while (!done) {
System.out.print("Enter the particle [Quark or Lepton]: ");
Scanner in = new Scanner(System.in);
String input = in.next();
if (input.equals("Quark")) {
System.out.println("Quark");
Quark q = new Quark();
processParticle(q);
} else if (input.equals("Lepton")) {
System.out.println("Lepton");
Lepton l = new Lepton();
processParticle(q);
} else {
done = true;
}
}
If you want to call processParticle() where compiler does not know the exact type of the particle, use double dispatch pattern:
// add method processParticle
public interface Particle{
...
void processParticle();
}
class Quark implements Particle {
void processParticle() {
Physics.processParticle(this);
}
}
class Lepton extends Particle {
void processParticle() {
Physics.processParticle(this);
}
}
public class Physics {
public static void main(String[] args) {
for (;;) {
System.out.print("Enter the particle [Quark or Lepton]: ");
Scanner in = new Scanner(System.in);
String input = in.next();
Particle p;
if (input.equals("Quark")) {
System.out.println("Quark");
p = new Quark();
} else if (input.equals("Lepton")) {
System.out.println("Lepton");
p = new Lepton();
} else {
break;
}
p.processParticle();
}
}
}
Then you can evolve to true visitor pattern, but reflection can and should be avoided here.

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