# Solved: JAVA Theory



## Geek4Life (Jan 30, 2008)

Without giving specifics i want the general on this: is it possible to pass an entire array between two classes (i.e. assuming we have Class A:

```
Pubcodelic Class A {
...
int x[][] = new int[#][#]
c b = new b();
...
c.doWhatever()
}
```
and then another class, b:

```
Public Class b {
...
public void doWhatever()
...
}
```
so, then how can i pass all the values in the array x, in class A, to class B?

Can it be done....semi-easily?


----------



## Chicon (Jul 29, 2004)

Hi Geek4Life,

Yes, it can be easily done, either by the constructor or by a setter.
Example :

```
[SIZE=2]
public class Test1 {
   private int[][] array;

   public Test1(int[][] array) {
      this.array = array;
   }

   ...
}

public class Test2 {
   private int[][] array;

   public Test2() {
   }

   public void setArray(int[][] array) {
      this.array = array;
   }
}

public class Demo {

   public static void main(String[] args) {
     int[][] a = new int[1][1];
     a[0][0] = 1;
     Test1 t1 = new Test1(a);
     Test2 t2 = new Test2();
     t2.setArray(a);	
  }
}[/SIZE]
```
In my example, all the classes Demo, Test1 and Test2 will work with the same object stored in memory.
If you mean to work with a replication of your array in order to preserve its initial values, then :

```
[SIZE=2]
public class Demo {

   public static void main(String[] args) {
     int[][] a = new int[1][1];
     a[0][0] = 1;
     Test1 t1 = new Test1([COLOR=Red]a.clone()[/COLOR]);
     Test2 t2 = new Test2();
     t2.setArray([COLOR=Red]a.clone()[/COLOR]);	
  }
}[/SIZE]
```


----------



## Geek4Life (Jan 30, 2008)

Thank you, I knew i could get an answer here. ill try working with that.


----------



## Geek4Life (Jan 30, 2008)

just 2 quick problems with your explanation:

1) Remember I'm an Amature at JAVA - I need to understand step by step how that code works/what it does

2) How do I take the modifications made in class B, back to class A?

Please explain the statements used - I have a Java book that teaches JAVA but it hardly scratches the surface of the surface of the capabilities of JAVA - if im going to learn the more advanced capabilities of JAVA I'm going to need help.


----------



## Chicon (Jul 29, 2004)

Here we go :

1)

```
[SIZE=2]
public class Test1 {
   [COLOR=BLUE]//an attribute[/COLOR]
   private int[][] array;

   [COLOR=BLUE]//The contructor is expecting an array[/COLOR]
   public Test1(int[][] array) {
      [COLOR=BLUE]/*[I]this.array[/I] refers to the only attribute of the Test1 class
      and [I]array[/I] refers to the passed parameter to the contructor
      the arrays must have the same type*/[/COLOR]
      this.array = array;
   }

   ...
}

public class Test2 {
   [COLOR=BLUE]//an attribute[/COLOR]
   private int[][] array;

   [COLOR=BLUE]/*The default constructor :
   when no constructor is present,
   the class will get the default one at compilation time*/[/COLOR]
   public Test2() {
   }

   [COLOR=BLUE]/*a method :
   it is called a [I]mutator[/I] as it modifies an attribute of the class*/[/COLOR]
   public void setArray(int[][] array) {
      [COLOR=BLUE]/*[I]this.array[/I] refers to the only attribute of the Test2 class
      and [I]array[/I] refers to the passed parameter to the method
      the arrays must have the same type*/[/COLOR]  
      this.array = array;
   }
}

public class Demo {

   [COLOR=BLUE]//the standard method that launches a Java program[/COLOR]
   public static void main(String[] args) {
      [COLOR=BLUE]/*build a 2 dimensional array of integers with 1 * 1 size :
      as an array is an extension of the [I][URL=http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html]Object[/URL][/I] class,
      [I]a[/I] will inherit its methods : clone(), toString(), and so on ...
      [I]System.out.println(a.toString())[/I] will display the hex value of the array pointer*/[/COLOR]
      int[][] a = new int[1][1];
      [COLOR=BLUE]//initialize the only item of the array to 1[/COLOR]
      a[0][0] = 1;
      [COLOR=BLUE]/*Create an instance of the Test1 class passing the pointer of [I]a[/I] as parameter
      the coding included inside the constructor of Test1 will be executed
      You may display the value of the pointer generated using [I]System.out.println(t1.toString())[/I]
      as Test1 is also an extension of the [I]Object[/I] class*/[/COLOR]
      Test1 t1 = new Test1(a);
      [COLOR=BLUE]//Create an instance of the Test2 class[/COLOR]
      Test2 t2 = new Test2();
      [COLOR=BLUE]//Pass a copy of the [I]a[/I] array to the method [I]setArray[/I][/COLOR]
      t2.setArray(a.clone());
  }
}
[/SIZE]
```
2) Simply by adding a method called an accessor.
In my class Test2, I will add an accessor this way :

```
[SIZE=2]
public class Test2 {
   private int[][] array;

   public Test2() {
   }

   public void setArray(int[][] array) {
      this.array = array;
   }
   
   [COLOR=BLUE]//Accessor[/COLOR]
   public int[][] getArray() {
      return this.array;
   }   
}
[/SIZE]
```
In my Demo class, I may have for example :

```
[SIZE=2]
      int[][] a = new int[1][1];
      a[0][0] = 1;
      Test2 t2 = new Test2();
      t2.setArray(a.clone());
      [COLOR=BLUE]int[][] b = t2.getArray()[/COLOR];
[/SIZE]
```


----------



## tomdkat (May 6, 2006)

Chicon said:


> Yes, it can be easily done, either by the constructor or by a setter.


Why must the array be a member of the target class for it to operate on it?


```
Public Class Test2 {
...
public void doWhatever(int x[][])
...
}

Public Class Test1 {
...
int x[][] = new int[#][#]
Test2 b = new Test2();
...
b.doWhatever(x)
}
```
Peace...


----------



## Chicon (Jul 29, 2004)

tomdkat said:


> Why must the array be a member of the target class for it to operate on it? ...


Hi tomdkat,

It is not mandatory to have the array as a member of a class.
My example is 'biased' toward _plain old Java objects_ for didactic reasons.


----------



## tomdkat (May 6, 2006)

Ok. 

Peace...


----------



## Geek4Life (Jan 30, 2008)

Wait...can it be done with only 2 classes or do i need a second one. (My intention is to create a sort-of defensive AI for the TicTacToe program i recieved assistance on earlier). I do not want you doing my work for me, which is what you kind of did with TicTacToe (nice as it was of you, it wasn't my code, my style of coding, etc., I just want to understand what i need to do so that i can do it myself), or do i need a third class to pass between the 2.


----------



## Chicon (Jul 29, 2004)

Geek4Life said:


> Wait...can it be done with only 2 classes or do i need a second one...


Yes, of course : one class, the starter and intializer of the program and the other one, the AI manager of TicTacToe.


----------



## Geek4Life (Jan 30, 2008)

But I need to be able to send the entire array in the starter class to the AI class so the AI class can then Analyze and modify it? How am I supposed to do that....that's all I'm really trying to figure out here.


----------



## Chicon (Jul 29, 2004)

You may do it this way :

```
[SIZE=2]
public class AI {
    public static void analyze(int[][] array) {
        int[][] a = array;
        // for example
        a[1][1] = 3;
    }
}

public class Starter {
    private static int[][] array = { {0,0,0}, {0,0,0}, {0,0,0} };

    public static void main(String[] args) {
        System.out.println("Before : " + array[1][1]);
        AI.analyze(array);
        System.out.println("After : " + array[1][1]);
    }
}
[/SIZE]
```


----------



## tomdkat (May 6, 2006)

Isn't that basically what I posted above? 

Peace...


----------



## Chicon (Jul 29, 2004)

Hi tomdkat,

Not exactly the same ! 
In my last example, there's no instantiation of the _AI_ class as its only method, _analyze_, is static (all static members of an application are preloaded into memory before the program starts effectively) and public(visible from outside its host class and package).
Therefore, there's no need to create an _AI_ object.


----------



## tomdkat (May 6, 2006)

Gotcha. :up:

Peace...


----------



## Geek4Life (Jan 30, 2008)

Does it matter if the original array isn't private?


----------



## Chicon (Jul 29, 2004)

No, it doesn't matter.
If you mean to work directly on the array of the starter class from a method of the AI class, you'll simply make the called class dependent on a specific attribute of the caller.
Therefore, it will make no sense to use a second class any more. You may as well implement the analyze method into the starter class.


----------



## Geek4Life (Jan 30, 2008)

You've given me good answers....and now I've got to do some thinking of my own and sort out what approach will work best for my situation, I guess I'm still trying to make the transition from procedural to Object-Oriented. So, then, I'll see where this leads, and see what new problems and questions pop-out of that, which I'm sure there will be.


----------



## Geek4Life (Jan 30, 2008)

How would I go about passing something to another class, and then return other stuff (more then one variable) to the original class..?


----------



## Chicon (Jul 29, 2004)

The methods of a Java class may accept many passed arguments but they only returns either no value or only one value.
But most of the time, we need methods that return more than one value.
In that situation, we have 2 possibilities :
- the expected values have all the same data type and the same role or function
- the expected values have either different data types or their role are different

For the first possibility, the solution is simple :
if you know the exact number of the values, you have to make the method return an array;
if the number of values is not known, then you have to use the List interface and you make the method return a _List_.

For the second possibility, you'll have to build an object that will contain the values you wish and make the method return that object.
To do so, you'll have to write a new class.
For example, in your Tic Tac Toe program, you want your AI class a method that gives the x and y of the cell to play.
You may write a class called Position that will contain the values.
Example :

```
[SIZE=2]
public class Position {
   private int x;
   private int y;
   public Position(int x, int y) {
      this.x = x;
      this.y = Y;
   }
   public int getX() {
      return x;
   }
   public int getY() {
      return y;
   }
}

public class AI {
   ...
   public Position analyze(int[][] board) {
      ...
      int x = [I]something[/I];
      int y = [I]something[/I];
      return new Position(x, y);
   }

public class Starter {
   ...
   ...
   int[][] b = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };
   AI ai = new AI();
   Position position = ai.analyze(b);
   int x = position.getX();
   int y = position.getY();
   ...
   ...
 }[/SIZE]
```


----------



## Geek4Life (Jan 30, 2008)

I see....this is going to turn out really interesting, and should be really rewarding when its all finished....this is definitely the route i need to be taking, so, ill see where i can go from there. Just a couple of Clarifications on your code for understanding....I've read about the "this" statement, but i still don't clearly understand its function.
2) The Method Position Analyze....That's references the Position Object (just the Method name, I know it does in the code - basicly why is it "Position Analyze", but when referenced in the starter program its just plain "Analyze")?


----------



## Chicon (Jul 29, 2004)

1) *this* is the reference of the current class instance.
In the _Position_ class of my example, _this.x_ and _this.y_ refer to the members of the class :
_private int x;
private int y;_

Also , in the statements : 
_this.x = x;
this.y = y;_
_x_ and _y_ are the arguments passed to the constructor.
It is a classic way to intialize the members of a class via its constructor.

2) _public Position analyze(int[][] board)_ : the word _Position_ in the method declaration means that the method must absolutely return a reference of an instance of the _Position_ class.
It's the reason why you see the statement _return new Position(x, y);_ at the end of the method.

A method that returns no value has the word _void_ in its declaration.
In the _Position_ class, the _getX()_ and _getY()_ methods must return a value of the data type _int_.


----------



## Geek4Life (Jan 30, 2008)

Okay, I think that actually makes since.


----------



## Geek4Life (Jan 30, 2008)

One other snippet of code that's a little confusing: *Position position = ai.analyze(b);*. I understand the front half is declaring a new object based off the position class, but i dont understand how the last half works when its not *new Object();*. Again, my textbook for Java provides no insight here...


----------



## Chicon (Jul 29, 2004)

If you look at the prior statement _AI ai = new AI();_ , I create a new instance of the _AI_ class and the reference of the instance is assigned to _ai_.
If you type _System.out.println(ai);_, the console will display the name of the class, _AI_, followed by hexadecimal values which represent the pointer of the object in memory.
Once I have the reference of a class, I may access to the public methods of the class, therefore, the notation _ai.analyze(b)_ makes sense.

Also, it is not mandatory to use variables to access the methods of a class, you may use _anonymous_ instance of a class.
Instead of having :
_AI ai = new AI();
Position position = ai.analyze(b);_
you may do :
_Position position = new AI().analyze(b);_
In both cases, _position_ will contain the reference of the _Position_ object returned by the _analyze_ method of the _AI_ instance.


----------



## Geek4Life (Jan 30, 2008)

I'm doing something wrong here and I don't know what....


```
import java.util.Random;
public class AI2 {
    Random g = new Random();
    private int x,y, x1, y1;
    private boolean placement = false;
    public Position analyze(int[][] Board, int round) {        
        if (round > 3) {
            for (int i = 0; i < 3; i++) {
                if (Board[i][0] == 1 && Board[i][1] == 1) {
                    x = i;
                    y = 2;
                    placement = true;
                    break;       
                } else if (Board[0][i] == 1 && Board[1][i] == 1) {
                    x = 2;
                    y = i;
                    placement = true;
                    break;
                }
            }
            if (placement = false) {
                if (Board[0][0] == 1 && Board[1][1] == 1) {
                    x = 2;
                    y = 2;
                } else if (Board[0][2] == 1 && Board[1][1] == 1) {
                    x = 2;
                    y = 0;
                }
            }
        } else {
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    if (Board[i][j] == 1) {
                        x1 = i;
                        y1 = j;
                        placement = true;
                        break;
                    }
                }
                if (placement == true) break;
            }
            do {
             if (x1 == 0) x = g.nextInt(2); else if (x1 == 1) x = g.nextInt(3); else if (x1 == 2) x = g.nextInt(2) + 1;
             if (y1 == 0) y = g.nextInt(2); else if (y1 == 1) y = g.nextInt(3); else if (y1 == 2) y = g.nextInt(2) + 1;
            } while (x == x1 && y == y1);
        }
        return new Position(x, y);
    } 
}
```
And then the Position class is exactly as you discribed it, no changes there. When I call *Position.getX();* and *Position.getY();* it always returns as 0,0.


----------



## Chicon (Jul 29, 2004)

At a first glance, it looks incomplete. Assuming that a cell may contain 3 values : one for each player and a default one when the cell is empty, you only focus the tests for one player and you don't check if a cell has already been used by the second player (the computer I guess).
I've tested your class with the number of rounds <=3, I get random numbers. 
The following part :

```
[SIZE=2]
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    if (Board[i][j] == 1) {
                        x1 = i;
                        y1 = j;
                        placement = true;
                        break;
                    }
                }
                if (placement == true) break;
            }
            do {
             if (x1 == 0) x = g.nextInt(2); else if (x1 == 1) x = g.nextInt(3); else if (x1 == 2) x = g.nextInt(2) + 1;
             if (y1 == 0) y = g.nextInt(2); else if (y1 == 1) y = g.nextInt(3); else if (y1 == 2) y = g.nextInt(2) + 1;
            } while (x == x1 && y == y1);
[/SIZE]
```
may be simplified this way :

```
[SIZE=2]
   int v;
   x = 0;
   y = 0;
   while (Board[x][y] == 1) {
      v = g.nextInt(9);
      x = v / 3;
      y = v % 3;
   }[/SIZE]
```


----------



## Geek4Life (Jan 30, 2008)

One last small problem, should be quick to solve, don't revise my code, just tell me in general what i need to do or what I'm doing wrong. From my tests this:

```
if (placement = false) {
                if (Board[0][0] == 1 && Board[1][1] == 1) {
                    x = 2;
                    y = 2;
                } else if (Board[0][2] == 1 && Board[1][1] == 1) {
                    x = 2;
                    y = 0;
                }
            }
```
appears to be getting ignored.


----------



## Chicon (Jul 29, 2004)

Without knowing the content of _Board_, I can't tell you what is wrong.

BTW, for the Tic Tac Toe algorithm :
- the number of rounds to consider may vary according to the player who starts first the game : if the computer starts the game itself, _threats_ are coming from the fourth round otherwise _threats_ are coming from the third;
- when the critical number of rounds is reached, the _analyze_ method should determine first if the computer can win the game, if so, the method returns immediately the position of the empty cell that will ends the game;
- if the computer can't win, then the method should determine where is the enemy's threat and return immediately the position of the empty cell to _block_;
- if there's no threat, the method returns the position of a random remaining empty cell : some preferences may be given to the strategic cells like the center cell, the corners cells.


----------



## Geek4Life (Jan 30, 2008)

It's meant to be a sheerly Defensive AI, for now, I plan on building a fuller AI later.


----------

