How to get the same instance of a class in Java? - java

Good morning,
I have one little problem.
I created one class named Map(). In this class there in one method that generate an Array. Then i created other two classes (Top and Bottom) that extend Map. Then I created 2 objects. One of Top and one of Bottom. I want to get the same array for the Top's object and for the Bottom's object. Here is the code Source:
public class Map{
public Map(){}
public int [] yTopValues()
{
int [] arrayTopY = new int[100];
for(int i=0;i<100;i++)
arrayTopY[i]=randomInt(-50,50);//it puts in i-th position an int between 50 and -50
return arrayTopY;
}
public int [] yBottomValues()
{
int [] arrayBottomY = yTopValues;
for(int i=0;i<100;i++)
arrayBottomY[i]=arrayBottomY[i]-250;
return arrayBottomY;
}
public int [] xValues()
{
int [] arrayX = new int[100];
for(int i=0;i<100;i++)
arrayX[i]=randomInt(0,50);//it puts in i-th position an int between 0 and 50
return arrayX;
}
//other stuff
}
public class TopMap extends Map{
public TopMap(){
this.area=new Area(new Polygon(
this.xValues,
this.yTopValues,
200)
);
}
public class BottomMap extends Map{
public BottomMap(){
this.area=new Area(new Polygon(
this.xValues,
this.yBottomValues,
200)
);
}
In the View class I created two objects one of TopMap and one of BottomMap then I drew the areas with g2.draw(topMap.area) and g2.draw(bottomMap.area)
I need the 2 polygons to be similar, but both of them are different because the method is executed twice. What should I do?
Thank you very much!!

The class Map does not hold the array. It is local only to the xValues() method. If you want the other classes to get that exact array do this:
/*
* Since this is a variable in the CLASS field, this object will
* be accessible to the child class.
*/
private int[] arrayX = new int[100];
public Map(){
createArrayX(); // This makes sure that the array is created, or else
// every value inside of it will be 0.
}
public void createArrayX(){ // Exact same thing as xValues(), but without the return type
for(int i=0;i<100;i++){
arrayX[i]=randomInt(0,50);
}
}
public int[] getArrayX(){ // The method that gets the array.
return arrayX;
}

Related

How to construct a two dimentional array in Java?

I am stuck in a very simple problem for more then 2 hours. I am trying to create a two dimensional array and fill it with a constructor. However, I couldn't pass this step.
public class Test
{
public State [][] test1= new State[4][3];//
public State test2[][]= new State[4][3];//
public State [][]test3;
public State test4[][];
public class State{
int position;
double reward;
int policy;
}
public Test(){
test1[1][1].position=1; // never worked
test2[1][3].position=2; //never worked
test3=new State[4][3];
test3[1][2].position=3; //never worked
test4=new State[4][3];
test4[2][2].position=4;//never worked
}
}
I am calling above function with following code
Test test= new Test();
Log.e("done","pass"); //I never reach here. the code always stuck on the constructor.
When you create the array :
public State [][] test1 = new State[4][3];
you are creating an array that can hold 4 * 3 State instances, but each position in the array is initialized to null.
You need to assign an instance of State to each position in the array before accessing it. If you don't, you'll get a NullPointerException.
For example :
public Test()
{
test1[1][1] = new State();
test1[1][1].position = 1;
....
}

Multiple methods in one program

I'm attempting to have an array (fishWeights) be set to the values that are found using a method. Except that when I try to compile this:
public class GoFishEdited {
public static void main(String[] args) {
System.out.println("\nProject 1, Stage 3\n");
Habitat h1 = new Habitat();
Habitat h2 = new Habitat();
int[] fishWeights = stockUp();
System.out.println("Start with some weights:");
for (int i : fishWeights) {
System.out.print(i + " ");
}
System.out.println("\n\nMake fish of those weights.\n");
Fish[] fishGroup = new Fish[fishWeights.length]; // array of Fish
for (int i=0; i < fishWeights.length; i++) {
fishGroup[i] = new Fish(fishWeights[i]); // make fish
}
}
}
It states that that the symbol stockUp() cannot be found. It is in this file:
public class Habitat {
ArrayList stringer = new ArrayList();
public int maxCount=25;
public int minCount=9;
public int maxWeight=10;
public int minWeight=1;
public int catchProbability=30; //0.3
public void stockUp(int[] fishArr){
int numofF = minCount + (int)(Math.random() * ((maxCount - minCount) + 1));
for(int i = 0; i<numofF; i++){
fishArr[i] = minWeight + (int)(Math.random() * ((maxWeight - minWeight) + 1));
}
}
public Habitat(){
}
public void addFish(Fish f) {
stringer.add(f);
}
public void removeFish(Fish f){
stringer.remove(f);
}
public void printFish(){
System.out.println(stringer);
}
}
So stockUp exists, I just can't seem to make getFishEdited to find it.
In java everything in an object.
So if you want to call method form a class should use
Habitat habitat = new Habitat();
habitat.stockUp();
stockUp() is an instance method of the Habitat class, so you need to create an instance of Habitat in your GoFishEdited class's main method in order to call it from GoFishEdited. You could call it on either instance of Habitat created, h1 or h2 Like this:
h1.stockUp();
Note that in the code you posted, you need to pass an array of integers as an argument to stockUp(), but it looks like in your code you are expecting stockUp() to return an int[]. If stockUp() is supposed to return an array of integers, then you need to change the method signature to look something like:
public int[] stockUp() {
//do whatever you want this method to do
return arrayOfInts;
}
You need to either create an instance of habitat using new Habitat to call the method in, or you need to make the method stockUp static and call it in the Habitat class using Habitat.stockUp.
Since you've created instances of Habitat in h1 and h2, call
h1.stockUp(fishArray)
Or
h2.stockUp(fishArray)
depending on what you mean to do. You declared the stockUp() method to accept an int[], so you'll need to pass it one--I called it fishArray, since you seem representing fish. Also, you've declare stockUp() as returning void, so don't expect it to return some value that you can assign to fishWeights. At some point you may find it's a good idea to introduce a Fish class to wrap that concept up better.

Calling methods from other classes using array objects in Java

Why does this code not work? It seems I cannot set the variable to '10' with the Array, but with a normal object it works.
What am I doing wrong?
Class- 1
public class apples {
public static void main(String[] args) {
carrots carrotObj = new carrots();
carrotObj.setVar(5);
System.out.println(carrotObj.getVar());
carrots carrotArray[] = new carrots[3];
carrotArray[1].setVar(10);
System.out.println(carrotArray[1].getVar());
}
}
Class- 2
public class carrots {
private int var = 0;
public int getVar() {
return var;
}
public void setVar(int var) {
this.var = var;
}
}
Console Output:
5
Exception in thread "main"
java.lang.NullPointerException
at apples.main(apples.java:17)
You created an array, but when an array of objects is created, they are all initialized to null -- the default value for object reference variables. You need to create some objects and assign them to slots in the array.
carrots carrotArray[] = new carrots[3];
// Place this code
carrotArray[1] = new carrots();
carrotArray[1].setVar(10);
You could do something similar for position 0 and 2.
Additionally, the Java convention is to capitalize class names, e.g. Carrots.
You need to initialize all the elements of the array; since they are not primitive data types their default value is null.
carrots carrotArray[] = new carrots[3];
for(int i=0; i < carrotArray.length; i++){
carrotArray[i] = new carrots();
}
carrotArray[1].setVar(10);
System.out.println(carrotArray[1].getVar());

Dealing with ArrayList and pass by reference

I'm using a arraylist to add states(the board state for the 8 puzzle). My problem is when I get the children of the state it changes the values stored in my array list. I'm assuming this is because ArrayList just stores pointers to the objects and not the values themselves. In order to fix this I create a new object every time before I store it into the ArrayList but I'm still having the same problem.
I will also try to follow naming conventions more often thanks for the tip.
private ArrayList<int[][]>VisitedBoard;
if(RuleNumber ==2){
//Here is my problem. This will change what is stored in VistedBoards
NextState = new State(FireRule.Rule2(WM.get_Board()));//Fire Rule
for(int j=0;j<VisitedBoards.size();j++){
//Meaning this will always be true
if(Arrays.equals(VisitedBoards.get(j), NextState.get_Board())){
Loop =true; //Loop to previous state
}
if(j==VisitedBoards.size()-1 && Loop ==false){ //If the next state is not any previously visited
NotALoop =true;
VisitedBoards.add(NextState.get_Board());
WM.set_Board(NextState.get_Board());
}
}
}
public int[][] Rule2(int [][] Board){//The FireRule Class
Find_BlankLocation(Board);
int temp;
State NewState;
temp = Board[BlankLocation[0]-1][BlankLocation[1]];
Board[BlankLocation[0]-1][BlankLocation[1]] = 0;
Board[BlankLocation[0]][BlankLocation[1]] = temp;
NewState = new State(Board);
return Board;
}
public class State { //State class
private int[][] Board;
private int[][] Goal;
private Boolean GoalFound;
public State(int[][] Start, int[][] goal){
Board = Start;
Goal = goal;
GoalFound=false;
}
public State(int[][] NewState){
Board=NewState;
}
public int[][] get_Goal(){
return Goal;
}
public int[][] get_Board(){
return Board;
}
public void set_Board(int[][] board){
Board = board;
}
public Boolean get_GoalFound(){
return GoalFound;
}
}
Containers like ArrayList work the same in all languages: they are called data structures because they organize storage/retrieval of objects. Obviously they don't store the fields of the objects themselves.
Trying to interpret your problem, maybe you don't want to share the boards between the list of visitedBoards and WM (whatever it means...). Then simply implement get_Board() to return a copy of the array instead of the Board object itself:
public int[][] get_Board(int[][] src) {
int[][] dst = new int[src.length][src[0].length];
for (int i = 0; i < src.length; i++) {
System.arraycopy(src[i], 0, dst[i], 0, src[i].length);
}
return dst;return dst;
}
Beside this, as others already told you, you'd really better to adopt the standard Java naming conventions, use meaningful names, and encapsulate your x, y and int[][] in real application classes.
Presumably, the new State object contains a pointer to the same arrayList as before. You'll want to manually copy the array out to a new one (a "deep clone" or "deep copy" as it is called). You might find this useful: Deep cloning multidimensional arrays in Java...?
Every time you create a new instance of State, you pass it the same array (whatever is returned by WM.get_Board()).
You then add that same array to VisitedBoards when you call VisitedBoards.add().
The fact that you're creating new State objects is irrelevant, because only the return value of NextState.get_Board() gets added to the list.
As a result, the list VisitedBoards always contains several references to the exact same array.
As Raffaele has suggested, you'll be fine if you make sure get_Board() returns a copy of the array in stead of a reference to the original (assuming that doesn't mess up logic that exists elsewhere).
The main thing I learned from this question is how important it is to follow naming conventions.
Your unconventional capitalization has made me dizzy!
Following these rules will make it much easier for others to understand your Java code:
class names should be capitalized (ie PascalCase)
variable names should be lowercase (ie camelCase)
do not use underscores in method names, class names, or variable names (they should only be used for constants)
always use meaningful names when possible
My advice is to create your own container object for their 2D array and implement deep copying.
For example:
package netbeans;
import java.util.Arrays;
public class Container
implements Cloneable
{
private int [] _data;
private int _sx;
private int _sy;
public int get(int x, int y)
{
try { return this._data[y*this._sx+x]; }
catch (Exception e) { throw new ArrayIndexOutOfBoundsException(); }
}
public void set(int x, int y, int value)
{
try { this._data[y*this._sx+x] = value; }
catch (Exception e) { throw new ArrayIndexOutOfBoundsException(); }
}
public Object Clone() { return new Container(this); }
public Container(int sizeX, int sizeY, int [] data)
{
this._sx = sizeX;
this._sy = sizeY;
this._data = data;
}
public Container(Container cont)
{
this._data = Arrays.copyOf(cont._data, cont._data.length);
}
}

initialise a array in one class and make accessible to another

this may seem daft i have a class called ship locations which i wish to store all my ships locations, ive extended it from my client class and simply called the set method as follows
sub.local being a multidimensional array from the ship class
sub.local = new int[2][2];
sub.local[0][0] =row;
sub.local[0][1]=col;
sub.local[1][0]=row;
sub.local[1][1] =col+1;
toServer.writeInt(row);
toServer.writeInt(col);
toServer.writeChar('s');
sub.placed=true;
setp1sub(sub.local);
When i print it back through another class it comes back with the location in the memory rather than the numbers i need. What is the reason for this
public class ShipLocations {
static int [][] p1sub;
public ShipLocations()
{
p1sub = new int[2][2];
}
public int[][] getp1sub()
{
return p1sub;
}
public void setp1sub(int[][] local) {
for (int i = 0;i <local.length;i++)
{
for(int j = 0;j<local.length;j++)
{
p1sub [i][j]= local[i][j];
}
}
}
}
would it be that im passing it as sub.local ?
output is [[I#a401c2
Instead of writing
System.out.println(yourArray);
use
// for multidemensional arrays:
System.out.println(Arrays.deepToString(yourArray));
// or for one dimemsional arrays:
System.out.println(Arrays.toString(yourArray));
Here is a link to the relevant JavaDoc.
For an explanation of your output, you can look at this answer.

Categories

Resources