Java Object Array Initialization - java

I am working on a java project which contains 3 classes and an object array in one of the classes. This project is ultimately supposed to move 4 entity objects around on a board by using the coordinates of the entity objects. These entity objects are stored in an array in the world class. My problem is with the array initialization in the world class. I am not sure how to set each element of the array equal to an object from the entity class and then access that object's coordinates to move it around on the board. The coordinates for the entity objects are initially set at 20x30 in a default constructor. Here is my code:
public class entity {
private int xcoordinate;
private int ycoordinate;
private String name;
private char symbol;
public entity(){
xcoordinate = 20;
ycoordinate = 30;
}
private entity(int newxcoor, int newycoor, String newname, char newsymbol){
xcoordinate = newxcoor;
ycoordinate = newycoor;
name = newname;
symbol = newsymbol;
}
public int getXCoor(){
return xcoordinate;
}
public int getYCoor(){
return ycoordinate;
}
}
public class world {
private entity[] ObArray = new entity[4];
public world(){
world test = new world();
}
public void draw(){
for (int i = 0; i < 4; i++)
{
//int x = ObArray[i].getXLoc();
//int y = ObArray[i].getYLoc();
}
}
}
public class mainclass {
public static void main(String[] args){
world worldob = new world();
//entity a = new entity();
//entity b = new entity();
//entity c = new entity();
//entity d = new entity();
worldob.draw();
}
}
My draw function and main function are not finished. After the array is initialized I will be able to finish the draw method using the entity get functions.
Thanks for your help.

That is one way of doing it. You can also define all of your entities inline like this:
private entity[] ObArray = {
new entity(0,0,"Entity1",'a'),
new entity(10,10,"Entity2",'b'),
new entity(20,20,"Entity3",'c'),
new entity(30,30,"Entity4",'d')
};
A better way may be to do an ArrayList instead of an array:
private List<entity> ObArray = new ArrayList<>();
ObArray.add(new entity(0,0,"Entity1",'a');
ObArray.add(new entity(10,10,"Entity2",'b');
ObArray.add(new entity(20,20,"Entity3",'c');
ObArray.add(new entity(30,30,"Entity4",'d');
To access each element you just need to get the element from the array and either get or set the properties you need:
ObArray[0].getXCoor();
ObArray[0].setXCoor(5);

Your problem is only creating new object of world inside world's constructor which throws stack overflow error, otherwise it is fine:
public world(){ world test = new world(); //REMOVE THIS LINE
}

You simply need to initialise the array. This can be done in the world constructor.
public world()
{
for (int i = 0; i < 4; i++)
{
ObArray[i] = new entity();
}
}
Then you can access the objects in your draw method, as you've shown:
public void draw()
{
for (int i = 0; i < 4; i++)
{
int x = ObArray[i].getXCoor();
int y = ObArray[i].getYCoor();
System.out.println("x" + x);
System.out.println("y" + y);
// Manipulate items in the array
// ObArray[i].setXCoor(10);
}
}
A more complete example, with the move functions added, and the class names capitalised:
public class Entity
{
private int xcoordinate;
private int ycoordinate;
private String name;
private char symbol;
public Entity()
{
xcoordinate = 20;
ycoordinate = 30;
}
private Entity(int newxcoor, int newycoor, String newname, char newsymbol)
{
xcoordinate = newxcoor;
ycoordinate = newycoor;
name = newname;
symbol = newsymbol;
}
public int getXCoor()
{
return xcoordinate;
}
public void setXCoor(int xcoordinate)
{
this.xcoordinate = xcoordinate;
}
public int getYCoor()
{
return ycoordinate;
}
public void setYcoor(int ycoordinate)
{
this.ycoordinate = ycoordinate;
}
public static void main(String[] args)
{
World worldob = new World();
worldob.draw();
worldob.move(0, 15, 30);
worldob.move(1, 45, 0);
worldob.move(2, 23, 27);
worldob.move(3, 72, 80);
worldob.draw();
}
}
class World
{
private final Entity[] ObArray;
public World()
{
this.ObArray = new Entity[4];
for (int i = 0; i < ObArray.length; i++)
{
ObArray[i] = new Entity();
}
}
public void move(int index, int xCoor, int yCoor)
{
if (index >= 0 && index < ObArray.length)
{
Entity e = ObArray[index];
e.setXCoor(xCoor);
e.setYcoor(yCoor);
}
}
public void draw()
{
for (Entity e : ObArray)
{
int x = e.getXCoor();
int y = e.getYCoor();
System.out.println("x" + x);
System.out.println("y" + y);
}
}
}

Related

Genetic algorithm Java, passing functions with two coordinates

I've written my first Genetic Algorithm in Java and I'm able to optimize functions with one argument x, but I don't know how to optimize functions with two arguments x and y. Algorithm class and main app works correctly so i send only Individual.java and Population.java. If I think correctly in genes I have only x-coordinate but I'm not sure how to add y-coordinate. Any advise will be helpfull.
Individual.java
public class Individual {
private int[] genes;
private int fitness;
private Random randomGenerator;
public Individual() {
this.genes = new int[Constants.CHROMOSOME_LENGTH];
this.randomGenerator = new Random();
}
public void generateIndividual() {
for(int i = 0; i < Constants.CHROMOSOME_LENGTH; i++) {
int gene = randomGenerator.nextInt(2);
genes[i] = gene;
}
}
public double f(double x) {
// return Math.pow(x,2);
return (Math.pow((1-x),2)) + (100*(Math.pow((1-Math.pow(x,2)),2)));
// return Math.sin(x)*((x-2)*(x-2))+3;
}
public double getFitness() {
double genesToDouble = genesToDouble();
return f(genesToDouble);
}
public double getFitnessResult() {
double genesToDouble = genesToDouble();
return genesToDouble;
}
public double genesToDouble() {
int base = 1;
double geneInDouble = 0;
for( int i =0; i < Constants.GENE_LENGTH; i++) {
if(this.genes[i] == 1)
geneInDouble += base;
base = base*2;
}
geneInDouble = (geneInDouble / 1024) * 10.1;
return geneInDouble;
}
public int getGene(int index) {
return this.genes[index];
}
public void setGene(int index, int value) {
this.genes[index] = value;
this.fitness = 0;
}
}
Population.java
public class Population {
private Individual[] individuals;
public Population(int populationSize) {
individuals = new Individual[populationSize];
}
public void initialize() {
for(int i = 0; i < individuals.length; i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
}
public Individual getIndividual(int index) {
return this.individuals[index];
}
//maksimum lub minimum
public Individual getFittestIndividual() {
Individual fittest = individuals[0];
for(int i =0; i < individuals.length; i++) {
if(getIndividual(i).getFitness() < fittest.getFitness())
fittest = getIndividual(i);
}
return fittest;
}
public int size() {
return this.individuals.length;
}
public void saveIndividual(int index, Individual individual) {
this.individuals[index] = individual;
}
}

Nullpointer Exception in function with 2d array as argument

I excepted that my functions in Level.java class allow me to make 2D array copy at any time in my program then change size of level array and fill it with values of copy and at last display it.
When I try to run my program it shows NullPointerException at line 24 in Level.java (a part which replaces the values).
Game.java Class
package main;
public class Game {
public static void main(String[] args) {
Level lvl = new Level();
char[][] exampleLevelTemplate = new char[][] {
{'#','#','#'},
{'#','#','#'},
{'#','#','#'}
};
lvl.setLevelSize(3,3);
lvl.setLevelLayout(exampleLevelTemplate);
lvl.displayLevel();
}
}
Level.java Class
package main;
public class Level {
private int levelWidth;
private int levelHight;
private char[][]level;
public void setLevelSize(int Width,int Height)
{
levelWidth = Width;
levelHight = Height;
char[][]level = new char[levelWidth][levelHight];
}
public void setLevelLayout(char[][]levelTemplate)
{
int a;
int b;
for(a=0; a < levelWidth; a++)
{
for(b=0; b<levelHight; b++)
{
level[a][b] = levelTemplate[a][b]; //Error happens here
}
}
}
public void displayLevel()
{
int a;
int b;
for(a=0; a < levelWidth; a++)
{
for(b=0; b<levelHight; b++)
{
System.out.println(level[a][b]);
}
}
}
}
Change your setLevelSize method to this:
public void setLevelSize(int Width,int Height)
{
levelWidth = Width;
levelHight = Height;
level = new char[levelWidth][levelHight];
}
You will see that line:
char[][]level = new char[levelWidth][levelHight];
was changed to:
level = new char[levelWidth][levelHight];
You need to just assign the array Object to array reference variable "level" and not create a local one and initialize it like you did.
You have been assigning value to a null array reference variable and therefore got NullPointerException.

How to retrieve an objects attribute information from within an array

I am trying to get the speed of a car object. Actually of all cars stored in an array and then pass that value to another variable.
So heres an example of what I have:
public class Car
{
private int speed;
public Car(int s)
{
speed = s;
}
public int getSpeed()
{
return speed;
}
public void setSpeed(int s)
{
speed = s;
}
}
I have a class that creates an array of cars.
public class Environment {
private Car[] garage;
private Random random;
public Environment(){
random = new Random();
populateGarage();
}
public void populateGarage()
{
garage = new Car[4];
int randomSpeed;
Car car;
for(int i= 0; i < garage.length; i++)
{
randomSpeed = random.nextInt(10);
if(randomSpeed < 5){
randomSpeed = randomSpeed +5;
}
car = new Car(carNames[i], randomSpeed);
garage.add(car);
System.out.println("car has speed "+ car.getSpeed());
}
All works fine up to this point. Now I am trying to access that value in a different class. Here's an example:
public class RaceDisplay extends JPanel implements ActionListener{
private int velX;
private int x;
private Car car;
private Environment env;
public RaceDisplay(){
x=0;
velX=env.getArray[0]... (the velocity value should be one of the car's speeds) <-------------
}
public void paintComponent(Graphics g){
super.paintComponent(g);
// (....)
}
public void actionPerformed(ActionEvent e) {
x=x+velX;
if(x>=650){
x=0;
x=x+velX;
}
}
I'm stuck on how to access that information through another class. Any help is most welcome.
because garage is a private field you will need a getter function set up in Environment
public Car getGarage (int index) {
return garage [index];
}
Of course if you are not interested in the Car object at all and just want the speed you could write a method to that like:
public int getSpeedOfCar (int index) {
return garage [index].getSpeed ();
}

Creating global array of objects (java)

So I'm working on a Space Invaders theme project, and I have most of my classes up and running and have started on the animation. Part of the process is the ship's weapons.
I have a class for the weapons, as below (Focus on the constructor):
/**
* #(#)Weapon.java
*
*
* #author Tristan Nel - 18179460
* #version 1.00 2015/3/4
*/
public class Weapon {
private String type;
private int damage;
private int rof; //rate of fire
private int orientation;
private int firingStage; //0 - not firing ; 1 - flash & recoil ; 2 - bullet
private String[] sprites; //Set of sprite image file names
public Weapon() {
}
public Weapon(String type, int damage, int rof, int orientation, int firingStage, String[] sprites)
{
this.type = type;
this.damage = damage;
this.rof = rof;
this.orientation = orientation;
this.firingStage = firingStage;
this.sprites = sprites;
}
//GET and SET Methods
public void setType(String type)
{
this.type = type;
}
public void setDamage(int damage)
{
this.damage = damage;
}
public void setROF(int rof)
{
this.rof = rof;
}
public void setOrientation(int orientation)
{
this.orientation = orientation;
}
public void setFiringStage(int firingStage)
{
this.firingStage = firingStage;
}
public void setSprites(String[] sprites)
{
this.sprites = sprites;
}
public String getType()
{
return this.type;
}
public int getDamage()
{
return this.damage;
}
public int getROF()
{
return this.rof;
}
public int getOrientation()
{
return this.orientation;
}
public int getFiringStage()
{
return this.firingStage;
}
public String[] getSprites()
{
return this.sprites;
}
}
In another class, which handles all elements on the game screen to be animated, I want to have a global array of hardcoded Weapon types that can be accessed as needed without fuss. I have attempted to do so at the top of the contents of the class:
/**
* #(#)GameScreen.java
*
*
* #author Tristan Nel - 18179460
* #version 1.00 2015/3/4
*/
import java.util.Scanner;
import java.io.*;
public class GameScreen {
private static final String HIGH_SCORE_FILE = "highScore.txt";
//Available Weapons
//UPDATED SINCE ORIGINAL POST
public static final Weapon[] WEAPONS = new Weapon[4];
WEAPONS[0] = new Weapon("Machinegun", 10, 20, 0, 0, {Graphics.MG_L_NORM, Graphics.MG_R_NORM});
WEAPONS[1] = new Weapon("Plasma MG", 20, 20, 0, 0, {Graphics.PMG_L_NORM, Graphics.PMG_R_NORM});
WEAPONS[2] = new Weapon("Photon Cannon", 40, 5, 0, 0, {Graphics.PC_L_NORM, Graphics.PC_R_NORM});
WEAPONS[3] = new Weapon("Alien Destabilizer", 60, 10, 0, 0, {Graphics.AD_L_NORM, Graphics.AD_R_NORM});
private Ship defender;
private Weapon equipped;
//private Invader[] aliens;
//private Bullet[] bullets;
private int score;
private int highscore;
private int lives;
public GameScreen() {
}
public GameScreen(Ship defender, int score, int lives)
{
this.defender = defender;
this.score = score;
this.lives = lives;
}
public void loadHighscore()
{
try
{
Scanner sc = new Scanner(new File(HIGH_SCORE_FILE));
this.highscore = Integer.parseInt(sc.next());
sc.close();
}
catch(FileNotFoundException fnf)
{
System.out.println(fnf);
this.highscore = 0;
}
}
public void saveHighScore(int highscore)
{
try
{
FileWriter write = new FileWriter(HIGH_SCORE_FILE);
PrintWriter pw = new PrintWriter(write);
pw.print(this.highscore);
pw.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
//GET and SET methods
public void setDefender(Ship defender)
{
this.defender = defender;
}
public void setScore(int score)
{
this.score = score;
}
public void setLives(int lives)
{
this.lives = lives;
}
public Ship getDefender()
{
return this.defender;
}
public int getScore()
{
return this.score;
}
public int getLives()
{
return this.lives;
}
}
This gives me the following error messages on each line that I try to add another element to the array:
UPDATED
https://drive.google.com/file/d/0B7ye7Ul2JDG2NDFDRTJNM1FCd0U/view?usp=sharing
It is highly frustrating..
I read somewhere that you have to create an object within a method? (Eg. main() )
But I tried that in my driver class and it made no difference...
Will appreciate any help/advice (:
There are multiple issues
You cannot have arbitrary code in the body of your class, e.g. the WEAPONS[0] = calls. However, you can initialize the array directly using new Type[]{} syntax. You could also use a static initializer static {} but this is not recommended.
Also, you need to use the constructor via new keyword, it's not just a method, i.e. new Weapon() not Weapon()
You cannot declare arrays using {}, i.e. new String[]{{Graphics.MG_L_NORM, Graphics.MG_R_NORM}} not {Graphics.MG_L_NORM, Graphics.MG_R_NORM}
Working version
public static final Weapon[] WEAPONS = new Weapon[] {
new Weapon("Machinegun", 10, 20, 0, 0, new String []{Graphics.MG_L_NORM, Graphics.MG_R_NORM}),
new Weapon("Plasma MG", 20, 20, 0, 0, new String []{Graphics.PMG_L_NORM, Graphics.PMG_R_NORM}),
new Weapon("Photon Cannon", 40, 5, 0, 0, new String []{Graphics.PC_L_NORM, Graphics.PC_R_NORM}),
new Weapon("Alien Destabilizer", 60, 10, 0, 0, new String []{Graphics.AD_L_NORM, Graphics.AD_R_NORM})
};
Actually I put it wrongly before but it looks like you need to call the constructor using the new operator like this.
arrayName[0] = new Weapon();
Since those classes seem somewhat static, something else to look into is using enums for this. This will help avoid complications when you have to search for a particular Weapon. A better design would be to have a WeaponType enum containing all the static immutable data in relation to a Weapon and have the Weapon class contain all the state data.

Creating an ArrayList of Employees

I have three classes
employee
production workers
shift supervisor class
My idea is to make production and shift supervisor extend the employee class and then create another class, EmployeeList to fill it with information about production workers and shift supervisors.
How can i get the names and info from employee class to iterate into an arraylist?
How can i add a random list of employees more than half being prod. workers and the rest shift supervisors?
Employee:
public class Employee {
public String EmployeeName;
public String EmployeeNumber;
public int hireyear;
public double WeeklyEarning;
public Employee()
{
EmployeeName = null;
EmployeeNumber = null;
hireyear = 0;
WeeklyEarning = 0;
}
public static final String[] Enum = new String[] {
"0001-A", "0002-B","0003-C","0004-D","0002-A",
"0003-B","0004-C","0005-D","0011-A", "0012-B",
"0013-C","0014-D","0121-A", "0122-B","0123-C" };
public static final String[] Ename = new String[] {
"Josh", "Alex", "Paul", "Jimmy", "Josh", "Gordan", "Neil", "Bob",
"Shiv", "James", "Jay", "Chris", "Michael", "Andrew", "Stuart"};
public String getEmployeeName()
{
return this.EmployeeName;
}
public String getEmployeeNumber()
{
return this.EmployeeNumber;
}
public int gethireyear()
{
return this.hireyear;
}
public double getWeeklyEarning()
{
return this.WeeklyEarning;
}
public String setEmployeeName(String EName)
{
return this.EmployeeName = EName;
}
public String setEmployeeNumber(String ENumber)
{
return this.EmployeeNumber = ENumber;
}
public int setEmployeehireyear(int Ehireyear)
{
return this.hireyear = Ehireyear;
}
public double setEmployeeweeklyearning(double Eweeklyearning)
{
return this.WeeklyEarning = Eweeklyearning;
}
}
ProductionWorker:
import java.util.Random;
public class ProductionWorker extends Employee {
public double HourlyRate;
public ProductionWorker()
{
super();
HourlyRate = 0;
}
public static void main(String[] args) {
ProductionWorker pw = new ProductionWorker();
Random rnd = new Random();
int count =0;
// adding random Employees.....
while(count<5)
{
int num= rnd.nextInt(Enum.length);
int decimal = rnd.nextInt(10);
double dec = decimal/10;
pw.setEmployeeName(Ename[num]);
pw.setEmployeeNumber(Enum[num]);
pw.setEmployeehireyear(rnd.nextInt(35) + 1980);
pw.setEmployeeweeklyearning(rnd.nextInt(5000) + 5000);
pw.setHourlyRate(rnd.nextInt(44) + 6 + dec);
System.out.println("EmployeeName: " + pw.getEmployeeName() + "\nEmployeeNumber: " + pw.getEmployeeNumber() +
"\nHireYear: " + pw.gethireyear() + "\nWeeklyEarning: " + pw.getWeeklyEarning() +
"\nHourlyRate: " + pw.getHourlyRate() +"\n");
count++;
}
}
public double getHourlyRate()
{
return this.HourlyRate;
}
public void setHourlyRate(double hourlyrate)
{
this.HourlyRate = hourlyrate;
}
}
ShiftSupervisor:
import java.util.Random;
public class ShiftSupervisor extends Employee{
public double YearlySalary;
public int GoalsCleared;
public ShiftSupervisor()
{
super();
YearlySalary = 0;
}
public static void main(String[] args) {
ShiftSupervisor S = new ShiftSupervisor();
Random rnd = new Random();
int count =0;
// adding random Employees.....
System.out.println("Adding Employees..");
while(count<5)
{
int num= rnd.nextInt(Enum.length);
S.setEmployeeName(Ename[num]);
S.setEmployeeNumber(Enum[num]);
S.setEmployeehireyear(rnd.nextInt(35) + 1980);
S.setEmployeeweeklyearning(rnd.nextInt(100) * 100);
S.setYearlySalary(rnd.nextInt(40000) + 40000);
System.out.println("EmployeeName:" + S.getEmployeeName() + "\nEmployeeNumber: " + S.getEmployeeNumber() +
"\nHireYear: " + S.gethireyear() + "\nWeeklyEarning: " + S.getWeeklyEarning() +
"\nearlySalary: " + S.getYearlySalary() +"\n");
count++;
}
}
// returns yearly salary
public double getYearlySalary()
{
return this.YearlySalary;
}
// returns goals cleared
public int getGoalsCleared()
{
return this.GoalsCleared;
}
// set yearly salary
public void setYearlySalary(double yearlysalary)
{
this.YearlySalary = yearlysalary;
}
}
The first thing I would do is have all necessary fields set in the constructor. If an Employee doesn't "exist" until it has a name, then that should be part of the constructor.
Then, I would suggest you consider renaming some of your fields. When I first saw Enum as a String[] and highlighted as a type, it took me a moment to figure out what exactly was going on. Renaming it to employeeNumbers could solve this.
Next, I think you should have an EmployeeGenerator class whose sole purpose is generating Employees.
public class EmployeeGenerator {
public ProductionWorker generateProductionWorker() {
Random rng = new Random();
int numberOfEmployeeNames = employeeNames.length;
String employeeName = employeeNames[rng.nextInt(numberOfEmployeeNames)];
int numberOfEmployeeNumbers = employeeNumbers.length;
String employeeNumber = employeeNumbers[rng.nextInt(numberOfEmployeeNumbers)];
ProductionWorker worker = new ProductionWorker(employeeName, employeeNumber);
int yearHired = rng.nextInt(100) + 1900;
worker.setHireYear(yearHired);
int hourlyRate = rng.nextInt(20) + 10;
worker.setHourlyRate(hourlyRate);
// any other fields...
return worker;
}
// method to generate shift supervisor
}
And then you can simply do
public static void main(String[] args) {
Random rng = new Random();
int numberOfEmployeesToGenerate = 1000;
int minimumNumberOfProductionWorkers = numberOfEmployeesToGenerate / 2;
int numberOfProductionWorkersToGenerate =
minimumNumberOfProductionWorkers + rng.nextInt(100);
int numberOfSupervisorsToGenerator =
numberOfEmployeesToGenerate - numberOfProductionWorkersToGenerate;
List<Employee> employees = new ArrayList<>();
EmployeeGenerator generator = new EmployeeGenerator();
for (int i = 0; i < numberOfProductionWorkersToGenerate; i++) {
ProductionWorker worker = generator.generateProductionWorker();
employees.add(worker);
}
for (int i = 0; i < numberOfSupervisorsToGenerate; i++) {
Supervisor supervisor = generator.generateSupervisor();
employees.add(supervisor);
}
}
This should hopefully give you a point in the right direction. This isn't perfect code, and there are other ways to refactor this to make it more maintainable and performant.
When you say you want to add a random list of employees, What do you mean exactly?
Currently you instantiate only one ProductionWorker and one ShiftSupervisor, change the values of the member variables, and print some text to StdOut.
Do you want to store instances in a list or is the console output sufficient?
Also, you have two main-methods. Which one will be performed? It might be better to have one Main class as an entry point for your application and from there create the instances.
In general you can do something like that:
public class Main {
public static void main(String[] args) {
List<Employee> emps = new ArrayList<>();
for (int i = 0; i < 5; i++) {
//create new employee
emps.add(newEmployee);
}
//do something with list
}
}

Categories

Resources