Results 1 to 14 of 14
  1. #1
    reis3k is offline Member
    Join Date
    Aug 2009
    Posts
    12
    Rep Power
    0

    Default Acting Java as if it's C problem

    Hello All!
    I'm surprised when I debugged my program. I was expecting a sequential assigning between values like in C, but it didn't work, and all my efforts are about to go if I don't solve this issue. Here is a code snippet:

    Java Code:
     private ArrayList<Game> generateMoves (Game game) {
    
            ArrayList<Game> moves = new ArrayList<Game>();
            Game tempGame = game;
    
            for (int generatedNumber = 0; generatedNumber < 7; generatedNumber++) {
                for (int row = 0; row < 6; row++) {
                    if (tempGame.board[row][generatedNumber] != 0) {
                        continue;
                    }else {
                        tempGame.board[row][generatedNumber] = 1;
                        tempGame.position = generatedNumber;
                        //tempGame.who = game.who; // ???
                        moves.add(tempGame);
                        tempGame = game;
                    }
                }
            }
            return moves;
        }
    I create a new Game object named tempGame, it get's it's value from parameter. Afterwards I modify this tempGame inside the for loop, BUT same modification is reflected to "game" object coming from parameter.

    My expectation was it won't change until I assign it, and therefore when I say "tempGame = game;" tempGame will get the very first value of game.

    I can just say that I didn't understand pointers in Java, but how can I reflect the thought I have. Thank you very much.

  2. #2
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    C can pass arguments to functions by value or reference, while Java methods always pass agruments by reference, so by doing:
    Java Code:
    Game tempgame = game;
    you simply created another reference that points to the same Game object. To circumvent this problem, you'll need to clone the game argument before modifying it, essentially creating a copy.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  3. #3
    reis3k is offline Member
    Join Date
    Aug 2009
    Posts
    12
    Rep Power
    0

    Default

    Actually, my idea was already to clone the game object as tempGame, but I don't know how to do. Is there any suggestion? Thanks

  4. #4
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    There are a few ways of achieving this, one is to create a new method inside your Game class, that returns a copy of the current object, or you could define a new constructor that takes a Game argument and does basically the same thing. An example of how to do this:
    Java Code:
    public class Example {
      private int a, b;
      public Example(int a, int b) {
        this.a = a; this.b = b;
      }
    
      public Example clone() {
        return new Example(a, b);
      }
    }
    Also note, this example is simple, because ints are primitives, not objects. In that case, you'd need to make sure you're cloning the fields of the class as well:
    Java Code:
    public class Example2 {
      private Integer a, b;
      public Example2(Integer a, Integer b) {
        this.a = a; this.b = b;
      }
    
      public Integer getA() {
        return a;
      }
    
      public void setA(Integer a) {
        this.a = a;
      }
    
      public Example2 badClone() {
        return new Example2(a, b);
      }
    
      public Example2 clone() {
        return new Example2(new Integer(a), new Integer(b));
      }
    
      public static void main(String[] args) {
        Example2 ex1, ex2, ex3;
        ex1 = new Example2(new Integer(1), new Integer(2));
        ex2 = ex1.badClone();
        ex3 = ex1.clone();
        ex1.setA(new Integer(5));
        System.out.println(ex2.getA()+" "+ex3.getA());
      }
    }
    Run this snippet to see what I mean.

    EDIT: hmm, I seem to have placed a foot in my mouth, as this example doesn't really prove what I'm trying to say :D
    Last edited by m00nchile; 10-17-2010 at 10:00 PM.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  5. #5
    reis3k is offline Member
    Join Date
    Aug 2009
    Posts
    12
    Rep Power
    0

    Default

    I'm a little confused all about this, and still couldn't apply the idea to my code.

    I created a Game object right after my main class definition to allow it to be accessed form all the methods of my Main class:

    Java Code:
    public class Main {
    
        Game currentGame = new Game();
    
        public static void main(String[] args) throws IOException {
    I used this Game object in a method in Main class like below, which is resulted as I wanted:
    Java Code:
      private void whoGoesFirst() {
            try {
                Scanner in = new Scanner(System.in);
                int turn = in.nextInt();
    
                if (turn == 2) {
                    currentGame.who = -1;
                    getNumber();
    and next method use one of the member field(?don't sure how it's called) of Game object by assigning it to an array:
    Java Code:
        private void getNumber() {
    
            int[][] tempBoard = new int[6][7];
            tempBoard = currentGame.board;
            tempBoard[0][0] = 1;
    The above code was first trying of mine. After the copy constructor idea I tried this:

    Java Code:
          tempBoard = new Game(currentGame).board;
    but again didn't work (currently I'm in a depressed mood and have high temperature). My expectation was that after *"tempBoard[0][0] = 1;"* part, only tempBoard's values will change, but it again affected currentGame's *board* array. What can I do for this situation?

    My Game class is here after copy constructor modification at the end :

    Java Code:
    public class Game {
        int[][] board;
        int position;
        int who;
    
        public Game () {
            board = new int[6][7];
            position = 0;
            who = 1;
        }
    
        public Game (int c) {
            board = new int[6][7];
            who = c;
        }
        public Game (int[][] a, int b, int c) {
            board = new int[6][7];
            board = a;
            position = b;
            who = c;
        }
    
        public Game (Game otherGame) {
            this.board = otherGame.board;
            this.position = otherGame.position;
            this.who = otherGame.who;
    
        }
    }

  6. #6
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Again, your problem is copying just the reference here:
    Java Code:
     public Game (Game otherGame) {
            [B]this.board = otherGame.board;[/B]
            this.position = otherGame.position;
            this.who = otherGame.who;
    
        }
    You'll have to make a new array (like you did), and then copy it element by element:
    Java Code:
     public Game (Game otherGame) {
            this.board = new int[6][7];
            copyContents(otherGame.board);
            this.position = otherGame.position;
            this.who = otherGame.who;
    
        }
    
    
    private void copyContents(int[][] a) {
      for(int i = 0; i < 6; i++)
        for(int j = 0; j < 7; j++)
          board[i][j] = a[i][j];
    }
    Because the thing is this:
    Java Code:
    int[] a = new int[5];
    int[] b = a;
    just means that both a and b point to the same array in memory. Any changes to a will be reflected in b and vice versa.
    Last edited by m00nchile; 10-17-2010 at 11:49 PM.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  7. #7
    reis3k is offline Member
    Join Date
    Aug 2009
    Posts
    12
    Rep Power
    0

    Default

    Brillient! Thank you very much again! I have some small questions to make my understanding full.
    Java Code:
     public Game (Game otherGame) {
            this.board = new int[6][7];
            copyContents(otherGame.board);
            this.position = otherGame.position;
            this.who = otherGame.who;
    
        }
    
     private void copyContents(int[][] a) {
      for(int i = 0; i < 6; i++)
        for(int j = 0; j < 7; j++)
          board[i][j] = a[i][j];
    }
    * why did we write this line " this.board = new int[6][7];"? Is it the same with board = new int[6][7];?
    * We created a copy method just for array. What about the "position" and "who" members?
    * Isn't it possible to copy array like assigment if their dimensions are the same size. I think this was the problem in my case from the beginning.
    * Apologizes if my questions are disturbing :) it's 2 AM in here and my brrain need sleeping more than my body.

  8. #8
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    The this keyword refers to the current object. In that line, this keyword could be skipped, it's mainly used to differentiate variables with the same name:
    Java Code:
    public class A {
      int a;
      public A(int a) {
        this.a = a; //set the value of the objects a field to value of argument a
      }
    }
    Next, the who and position variables are of the type int, and therefore primitives. Primitives in Java are always passed by value, not reference. As a guide, if the type starts with a lower case letter, it's a primitive (int, double, boolean), if it starts with an upper case letter, it's an object (String, Character, Integer). Next, these two lines:
    Java Code:
    board = new int[6][7];
    board = a;
    The first line creates a new array in memory, and saves the reference in the board variable, the next line sets the reference to an existing array, making the first line useless (the reference to the newly created array is lost).
    The C equivalent of this would be:
    Java Code:
    int a = 5, b = 4;
    int *pa = &a;
    *pa = &b;
    First you set the pointer to a, then to b, losing the reference to a in the process.
    Btw, don't feel bad about posting questions about referencing, a very similar problem kept me up all night while doing a project for my university.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  9. #9
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

  10. #10
    reis3k is offline Member
    Join Date
    Aug 2009
    Posts
    12
    Rep Power
    0

    Default

    Yes, but I got the answer from this forum not the other one. I'm about to deadline of my project that's the only reason.

  11. #11
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    A simple way of avoiding tension about cross posting is including the link to your other post in the first post. That way, if someone wants to help, they can check the other forum if a solution has been found already, and not waste their time.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  12. #12
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,533
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by m00nchile View Post
    C can pass arguments to functions by value or reference, while Java methods always pass agruments by reference
    Rubbish; both C and Java pass their arguments by value. C can pass pointers to memory and Java passes references to objects but they are both passed by value.

    kind regards,

    Jos

  13. #13
    reis3k is offline Member
    Join Date
    Aug 2009
    Posts
    12
    Rep Power
    0

    Default

    Quote Originally Posted by m00nchile View Post
    A simple way of avoiding tension about cross posting is including the link to your other post in the first post. That way, if someone wants to help, they can check the other forum if a solution has been found already, and not waste their time.
    Thanks for the tip. I'll apply it from now on for every forums that I anticipated.

  14. #14
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Thanks for the tip. I'll apply it from now on

    Thanks. I wasn't trying to "tell you off" - or add to your deadline tension! - just letting everyone know that the discussion was going on in two locations at once. It probably is a good idea to be upfront about multiposting. The guy who got annoyed at the other forum is legendary for the amount of help he gives people learning Java: you want him on your side!

Similar Threads

  1. Having a problem with Java...
    By sek in forum New To Java
    Replies: 17
    Last Post: 05-29-2010, 04:28 PM
  2. java problem
    By Mj Shine in forum New To Java
    Replies: 5
    Last Post: 08-15-2009, 05:09 AM
  3. Problem in java
    By saytri in forum New To Java
    Replies: 4
    Last Post: 01-16-2008, 10:09 PM
  4. Problem in java
    By saytri in forum New To Java
    Replies: 6
    Last Post: 01-09-2008, 04:13 PM
  5. java SE 6 problem
    By techlance in forum Java Applets
    Replies: 1
    Last Post: 06-28-2007, 10:10 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •