Exception in thread "main" java.lang.NullPointerException why? - java

The error is:
Exception in thread "main" java.lang.NullPointerException
I would like to make a tic tac toe console game for my university. This is the code below
the main program:
import acm.program.*;
public class askisi1d extends Program {
public void run(){
tictac player[];
player=new tictac[2];
player[0]=new tictac("baggelis");
player[1]=new tictac("Giorgaras");
player[0].setMove("1 2");
println(tictac.drawTable());
}
}
This is the class code:
import java.util.*;
import acm.program.*;
public class tictac{
private String name;
int [][]table=new int [][]{
{8,1,6},
{3,5,7},
{4,9,2}
};
int activePlayer;
boolean [][]takenSquare= new boolean [2][2];
int [][]playerTable; //gia tin niki
static tictac[] player;
private int row; //<---
private int col; //""
public tictac(String name){
this.name=name;
playerTable=new int[2][2];
activePlayer=0;
}
public boolean isValidMove(int row,int col){
return (row>0&&row<4&&col>0&&col<4&&takenSquare[row-1][col-1]==false);
}//isValidmove
public void setMove (String move){
StringTokenizer tokenizer=new StringTokenizer(move);
this.row= Integer.parseInt(tokenizer.nextToken());
this.col= Integer.parseInt(tokenizer.nextToken());
if (isValidMove(row-1,col-1)){
player[activePlayer].takenSquare[row-1][col-1]=true;
player[activePlayer].playerTable[row-1][col-1]=table[row-1][col-1];
}
activePlayer=1-activePlayer;
}
public static String drawTable(){
String a="";
a+=(drawSquare(0,0)+"|");
a+=(drawSquare(0,1)+"|");
a+=(drawSquare(0,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(1,0)+"|";
a+=drawSquare(1,1)+"|";
a+=(drawSquare(1,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(2,0)+"|";
a+=drawSquare(2,1)+"|";
a+=(drawSquare(2,2));
return"a";
}
public static String drawSquare(int x,int y){
if (player[0].isTaken(x,y)) {
return "O";
} else if (player[1].isTaken(x,y)) return "X";
else return " ";
}
public boolean isTaken(int x,int y) {
return takenSquare[x][y];
}
}

A couple of problems:
You already have static play array defined within your tictac class. run() defines a local copy of it and as soon as you invoke drawTable(), it takes the uninitialized static array ignoring what you have in run().
You can either make a proper use of static variables by initializing them.
Quick and dirty check is to write the main method within your tictac class and comment out the local version of the array.
Something like:
public static void main(String[] args){
//TicTac player[];
player=new TicTac[2];
player[0]=new TicTac("baggelis");
player[1]=new TicTac("Giorgaras");
player[0].setMove("1 2");
System.out.println(TicTac.drawTable());
}
As pointed out in the comments, now you would run into ArrayIndexOutOfBounds exception hence make those changes, modified code below:
import java.util.StringTokenizer;
public class TicTac{
private String name;
int [][]table=new int [][]{
{8,1,6},
{3,5,7},
{4,9,2}
};
int activePlayer;
boolean [][]takenSquare= new boolean [3][3];
int [][]playerTable; //gia tin niki
static TicTac[] player;
private int row; //<---
private int col; //""
public TicTac(String name){
this.name=name;
playerTable=new int[2][2];
activePlayer=0;
}
public boolean isValidMove(int row,int col){
return (row>0&&row<4&&col>0&&col<4&&takenSquare[row-1][col-1]==false);
}//isValidmove
public void setMove (String move){
StringTokenizer tokenizer=new StringTokenizer(move);
this.row= Integer.parseInt(tokenizer.nextToken());
this.col= Integer.parseInt(tokenizer.nextToken());
if (isValidMove(row-1,col-1)){
player[activePlayer].takenSquare[row-1][col-1]=true;
player[activePlayer].playerTable[row-1][col-1]=table[row-1][col-1];
}
activePlayer=1-activePlayer;
}
public static String drawTable(){
String a="";
a+=(drawSquare(0,0)+"|");
a+=(drawSquare(0,1)+"|");
a+=(drawSquare(0,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(1,0)+"|";
a+=drawSquare(1,1)+"|";
a+=(drawSquare(1,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(2,0)+"|";
a+=drawSquare(2,1)+"|";
a+=(drawSquare(2,2));
return"a";
}
public static String drawSquare(int x,int y){
if (player[0].isTaken(x,y)) {
return "O";
} else if (player[1].isTaken(x,y)) return "X";
else return " ";
}
public boolean isTaken(int x,int y) {
return takenSquare[x][y];
}
public static void main(String[] args){
//TicTac player[];
player=new TicTac[2];
player[0]=new TicTac("baggelis");
player[1]=new TicTac("Giorgaras");
player[0].setMove("1 2");
System.out.println(TicTac.drawTable());
}
}

This should make your code work. At least it won't throw a NullPointerException at drawSquare()
public class tictac {
... //rest of the code
static tictac[] player = {
new tictac( "PlayerName1" ),
new tictac( "PlayerName2" ),
};
... //more code
}
EDIT: Ok, perhaps I wasn't as straightforward as I thought. This is the full code for the class tictac that I want you to run
import java.util.*;
import acm.program.*;
public class tictac{
private String name;
int [][]table=new int [][]{
{8,1,6},
{3,5,7},
{4,9,2}
};
int activePlayer;
boolean [][]takenSquare= new boolean [2][2];
int [][]playerTable; //gia tin niki
static tictac[] player = {
new tictac( "PlayerName1" ),
new tictac( "PlayerName2" ),
};
private int row; //<---
private int col; //""
public tictac(String name){
this.name=name;
playerTable=new int[2][2];
activePlayer=0;
}
public boolean isValidMove(int row,int col){
return (row>0&&row<4&&col>0&&col<4&&takenSquare[row-1][col-1]==false);
}//isValidmove
public void setMove (String move){
StringTokenizer tokenizer=new StringTokenizer(move);
this.row= Integer.parseInt(tokenizer.nextToken());
this.col= Integer.parseInt(tokenizer.nextToken());
if (isValidMove(row-1,col-1)){
player[activePlayer].takenSquare[row-1][col-1]=true;
player[activePlayer].playerTable[row-1][col-1]=table[row-1][col-1];
}
activePlayer=1-activePlayer;
}
public static String drawTable(){
String a="";
a+=(drawSquare(0,0)+"|");
a+=(drawSquare(0,1)+"|");
a+=(drawSquare(0,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(1,0)+"|";
a+=drawSquare(1,1)+"|";
a+=(drawSquare(1,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(2,0)+"|";
a+=drawSquare(2,1)+"|";
a+=(drawSquare(2,2));
return"a";
}
public static String drawSquare(int x,int y){
if (player[0].isTaken(x,y)) {
return "O";
} else if (player[1].isTaken(x,y)) return "X";
else return " ";
}
public boolean isTaken(int x,int y) {
return takenSquare[x][y];
}
}

Related

Write out the table in other method

Hey i want to write out table in second method.
In first i changed int x into table(each digit in other array index) and in second method i want to write out the table. How to do it ?
int tab [] =new int [4];
public int[] change(int x) {
System.out.print(tab[0]=x/1000);
System.out.print(tab[1]=(x/100)%10);
System.out.print(tab[2]=(x/10)%10);
System.out.println(tab[3]=x%10);
System.out.println(tab.toString());
return tab;
}
public void writeout(int a[]) {
this.tab=a;//how to connect tab from change() with int a[]
for( int i=0;i<=3;i++) {
System.out.println(a[i]);
}
You can use newest Java 8 API to print your array. Your code may look like this:
import java.util.Arrays;
public class App {
int tab[] = new int[4];
public int[] change(int x) {
tab[0] = x/1000;
tab[1] = (x/100)%10;
tab[2] = (x/10)%10;
tab[3] = x%10;
return tab;
}
public void writeout(int array[]) {
Arrays.stream(array).forEach(System.out::println);
}
public static void main(String[] args) {
App app = new App();
app.writeout(app.change(2));
}
}
I fiddled with it. It appears to work after adding a closing brace at the end. tab.toString() doesn't result in sensible results though.
public class MyClass {
public static void main(String args[]) {
MyClass c = new MyClass();
c.writeout(c.change(3));
}
public int[] change(int x) {
int tab [] =new int [4];
System.out.print(tab[0]=x/1000);
System.out.print(tab[1]=(x/100)%10);
System.out.print(tab[2]=(x/10)%10);
System.out.println(tab[3]=x%10);
System.out.println(tab.toString());
return tab;
}
public void writeout(int a[]) {
for( int i=0;i<=3;++i) {
System.out.println(a[i]);
}
}
}
If you want to use class fields, then you could do it like this:
public class MyClass {
public static void main(String args[]) {
MyClass c = new MyClass();
c.change(3);
c.writeout();
}
private int tab [] = new int [4];
public void change(int x) {
System.out.print(tab[0]=x/1000);
System.out.print(tab[1]=(x/100)%10);
System.out.print(tab[2]=(x/10)%10);
System.out.println(tab[3]=x%10);
}
public void writeout() {
for( int i=0;i<=3;i++) {
System.out.println(tab[i]);
}
}
}

Exception in thread "main" java.lang.NullPointerException when Accessing a Variable in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
package model;
import model.interfaces.DicePair;
import model.interfaces.Player;
public class SimplePlayer implements Player{
private String playerName;
private int points;
private String playerId;
private int bet;
DicePair dicePair;
public SimplePlayer(String playerId,String playerName,int points){
this.playerId=playerId;
this.playerName=playerName;
this.points=points;
}
public String getPlayerName(){
return playerName;
}
public void setPlayerName(String playerName){
this.playerName=playerName;
}
public int getPoints(){
return points;
}
public void setPoints(int points){
this.points=points;
}
public String getPlayerId(){
return playerId;
}
public boolean placeBet(int bet){
if(bet>getPoints()){
return false;
}
else{
this.bet=bet;
return true;}
}
public int getBet(){
return bet;
}
public DicePair getRollResult(){
return dicePair;
}
public void setRollResult(DicePair rollResult){
this.dicePair=rollResult;
}
public String toString(){
return "Player: id="+playerId+", name="+playerName+", points="+points;
}
}
// this class have the points value
package model;
import java.util.ArrayList;
import java.util.Collection;
import model.interfaces.DicePair;
import model.interfaces.GameEngine;
import model.interfaces.GameEngineCallback;
import model.interfaces.Player;
public class GameEngineImpl implements GameEngine {
SimplePlayer simplePlayer;
public static int NUM_FACES = 6;
Collection<Player> players= new ArrayList<Player>();
GameEngineCallback gameEngineCallback;
DicePair dicePair;
DicePair dicePair2;
Player player;
public void rollPlayer(Player player, int initialDelay,
int finalDelay, int delayIncrement){
for(int i= initialDelay; i<=finalDelay;i+=delayIncrement){
int dice1=(int)(Math.random()*NUM_FACES+1);
int dice2=(int)(Math.random()*NUM_FACES+1);
DicePairImpl dicePairImpl=new DicePairImpl(dice1,dice2);
gameEngineCallback.intermediateResult(player,dicePairImpl,this);
try {
Thread.sleep(initialDelay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int dice1=(int)(Math.random()*NUM_FACES+1);
int dice2=(int)(Math.random()*NUM_FACES+1);
DicePairImpl dicePairImpl=new DicePairImpl(dice1,dice2);
gameEngineCallback.result(player,dicePairImpl,this);
player.setRollResult(dicePairImpl);
dicePair=dicePairImpl;
};
public void addPlayer(Player player){
players.add(player);
};
public boolean removePlayer(Player player){
if(players.contains(player)==true){
players.remove(player);
return true;
}
return false;
};
public void calculateResult(){
.....
int points=simplePlayer.getPoints();// get error from here which is Exception in thread "main" java.lang.NullPointerException
System.out.println(points);
}
}
In this class, for the method calculateResult(), i need to get the points value for player. i tried to write int points=simplePlayer.getPoints(); i keep causing error, which i am lost and cannot get the points value.
The error is as follows:
Exception in thread "main" java.lang.NullPointerException
public class SimplePlayer implements Player{
private String playerName;
private int points;
private String playerId;
private int bet;
DicePair dicePair;
public SimplePlayer(String playerId,String playerName,int points){
this.playerId=playerId;
this.playerName=playerName;
this.points=points;
}
// this is the simplePlayer class
The reason why you're getting the error is because simplePlayer is null. You probably didn't initialize simplePlayer using its constructor. Please post the code between the declaration and the usage if you wish for me to confirm. To use the constructor, you should probably use:
simplePlayer = new SimplePlayer( 1, "Adam", 0 );
You can further test it by executing the following line before the simplePlayer.getPoints() call.
if( simplePlayer == null )
System.out.println( "simplePlayer is null!" );
int points=simplePlayer.getPoints();
EDIT:
After looking through the code, the OP found that this.simplePlayer=simplePlayer solve the issue to not make it null.

How to Count Number of Instances of a Class

Can anyone tell me how to count the number of instances of a class?
Here's my code
public class Bicycle {
//instance variables
public int gear, speed, seatHeight;
public String color;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
}
//getters and setters
public int getGear() {
return gear;
}
public void setGear(int Gear) {
this.gear = Gear;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int Speed){
this.speed = Speed;
}
public int getSeatHeight() {
return seatHeight;
}
public void setSeatHeight(int SeatHeight) {
this.seatHeight = SeatHeight;
}
public String getColor() {
return color;
}
public void setColor(String Color) {
this.color = Color;
}
}//end class
public class Variable extends Bicycle {
public Variable(int gear, int speed, int seatHeight, String color) {
super(gear, speed, seatHeight, color);
}
}//end class
public class Tester {
public static void main(String args[]){
Bicycle bicycle1 = new Bicycle(0, 0, 0, null);
bicycle1.setColor("red");
System.out.println("Color: "+bicycle1.getColor());
bicycle1.setSeatHeight(4);
System.out.println("Seat Height: "+bicycle1.getSeatHeight());
bicycle1.setSpeed(10);
System.out.println("Speed: "+bicycle1.getSpeed());
bicycle1.setGear(6);
System.out.println("Gear: "+bicycle1.getGear());
System.out.println("");//space
Bicycle bicycle2 = new Bicycle(0, 0, 0, null);
bicycle2.setColor("black");
System.out.println("Color: "+bicycle2.getColor());
bicycle2.setSeatHeight(6);
System.out.println("Seat Height: "+bicycle2.getSeatHeight());
bicycle2.setSpeed(12);
System.out.println("Speed: "+bicycle2.getSpeed());
bicycle2.setGear(6);
System.out.println("Gear: "+bicycle2.getGear());
System.out.println("");//space
}//end method
}//end class
The class variable is to be used to keep count of the number of instances of the Bicycle class created and the tester class creates a number of instances of the Bicycle class and demonstrates the workings of the Bicycle class and the class variable. I've looked all over the internet and I can't seem to find anything, could someone show me how to do it please, thanks in advance :)
Since static variables are initialized only once, and they're shared between all instances, you can:
class MyClass {
private static int counter;
public MyClass() {
//...
counter++;
}
public static int getNumOfInstances() {
return counter;
}
}
and to access the static field counter you can use MyClass.getNumOfInstances()
Read more about static fields in the JLS - 8.3.1.1. static Fields:
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (ยง12.4).
Note that counter is implicitly set to zero
Pleae try the tool of java
jmap -histo <PDID>
Out put
num #instances #bytes class name
----------------------------------------------
1: 1105141 97252408 java.lang.reflect.Method
2: 3603562 86485488 java.lang.Double
3: 1191098 28586352 java.lang.String
4: 191694 27035744 [C
In addition, you should override finalize method to decrement the counter
public class Bicycle {
...
public static int instances = 0;
{
++instances; //separate counting from constructor
}
...
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
}
#Override
protected void finalize() {
super.finalize();
--instances;
}
}
You should have in mind that static variables are CLASS scoped (there is no one for each instance, only one per class)
Then, you could demonstrate instance decrement with:
...
System.out.println("Count:" + Bicycle.getNumOfInstances()); // 2
bicycle1 = null;
bicycle2 = null;
System.gc(); // not guaranteed to collect but it will in this case
Thread.sleep(2000); // you expect to check again after some time
System.out.println("Count again:" + Bicycle.getNumOfInstances()); // 0
why not using a static counter?
public class Bicycle {
private static int instanceCounter = 0;
//instance variables
public int gear, speed, seatHeight;
public String color;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
instanceCounter++;
}
public int countInstances(){
return instanceCounter;
}
........
You just need static counter in class.
public class Bicycle {
private static volatile int instanceCounter;
public Bicycle() {
instanceConter++;
}
public static int getNumOfInstances() {
return instanceCounter;
}
protected void finalize() {
instanceCounter--;
}
}
As mentioned in many comments finalize() is not recommended to use so there could be another approach to count the Bicycle instances -
public class Bicycle {
private static final List<PhantomReference<Bicycle>> phantomReferences = new LinkedList<PhantomReference<Bicycle>>();
private static final ReferenceQueue<Bicycle> referenceQueue = new ReferenceQueue<Bicycle>();
private static final Object lock = new Object();
private static volatile int counter;
private static final Runnable referenceCleaner = new Runnable() {
public void run() {
while (true) {
try {
cleanReferences();
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
static {
Thread t = new Thread(referenceCleaner);
t.setDaemon(true);
t.start();
}
private Bicycle() {
}
public static Bicycle getNewBicycle() {
Bicycle bicycle = new Bicycle();
counter++;
synchronized (lock) {
phantomReferences.add(new PhantomReference<Bicycle>(new Bicycle(), referenceQueue));
}
System.out.println("Bicycle added to heap, count: " + counter);
return bicycle;
}
private static void cleanReferences() {
try {
PhantomReference reference = (PhantomReference) referenceQueue.remove();
counter--;
synchronized (lock) {
phantomReferences.remove(reference);
}
System.out.println("Bicycle removed from heap, count: " + counter);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getNumOfBicycles() {
return counter;
}
}
public class BicycleTest {
public static void main(String[] args) {
int i = 0;
while (i++ < 1000) {
Bicycle.getNewBicycle();
}
while (Bicycle.getNumOfBicycles() > 0) {
try {
Thread.sleep(1000);
System.gc(); // just a request
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Alternatively, you can create a counter with an initializer block and a static variable.
class SomeClass
{
private static int instanceCounter;
{
instanceCounter++;
}
}
Initializer blocks get copied by the compiler into every constructor, so, you will have to write it once no matter how many constructors you will need (As referred into the above link). The block in {} runs every time you create a new object of the class and increases the variable counter by one.
And of course get the counter by something like:
public static int getInstanceCounter()
{
return instanceCounter;
}
or directly
int numOfInstances = SomeClass.instanceCounter;
If you do not make numOfInstances private
One basic approach is to declare a static numeric member field thats incremented each time the constructor is invoked.
public class Bicycle {
//instance variables
public int gear, speed, seatHeight;
public String color;
public static int bicycleCount = 0;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
bicycleCount++;
}
...
}
If you want to count and test instances based on the number of objects created, you can use a loop to see what really is happening. Create a constructor and use a static counter
public class CountInstances {
public static int count;
public CountInstances() {
count++;
}
public int getInstaces() {
return count;
}
public static void main(String []args) {
for(int i= 0; i<10; i++) {
new CountInstances();
}
System.out.println(CountInstances.count);
}
}
public class Number_Objects {
static int count=0;
Number_Objects(){
count++;
}
public static void main(String[] args) {
Number_Objects ob1=new Number_Objects();
Number_Objects ob2=new Number_Objects();
Number_Objects obj3=new Number_Objects();
System.out.print("Number of objects created :"+count);
}
}

Random generator does not work it always shows 0

import java.util.Random;
public class PouAbilites {
protected int Health;
public int getHealth(){
return this.Health;
}
public void setHealth(final int Health){
final Random random = new Random();
final int randomInt = random.nextInt(100)+1;
this.Health=randomInt;
}
PouAbilites(){
this.Eletero=getEletero();
}
public void onscreen(){
System.out.println("Health: "+ this.Health);
}
}
The main function is included in an other class:
package KotelezoProgram;
public class Main {
public static void main(final String[] args) {
final PouAbilites Pou = new PouAbilites();
Pou.onscreen();
}
}
call setHealth() in between
PouAbilites Pou = new PouAbilites();
Pou.onscreen();
calls
Calling onscreen() before setHealth() will return 0 because this.Health is just initialized in the Pou object to zero.

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