James Morrish
James Morrish

Reputation: 11

Transferring variables from class to class in Java

I have been having some issues transferring Variable data from Class to Class in Java whilst completing a Monopoly-type text-based game.

I have been trying to transfer the roll1 and roll2 variables from the Dice class into the Board Class, but for some reason the data is not being transferred properly, and when I return the combined data from the 2 Rollin the Board class, it just comes back as 0.

Here are my classes:

public class Dice {

    static int dots, roll1, roll2, flag;
    Random number = new Random();

    public Dice(){
         dots = number.nextInt(6)+1 ;
    }

    public void roll1(){
        roll1 = number.nextInt(dots)+1;
    }

    public void roll2(){
        roll2 = number.nextInt(dots)+1;
    }

    public int getDots1(){
        return roll1;
    }

    public int getDots2(){
        return roll2;
    }

    public String getSame(){
        if(roll1 == roll2){
            flag++;
            return("Your rolls were the same");
        }
        else{
            return(" ");
        }

    }
}

public class Board {
    static int roll1 = Dice.roll1;
    static int roll2 = Dice.roll2;
    public static int i;
    public int Turn = 0;
    public int totalP = 0;
    public static int Pos = 0;
    public static int[] Players= {1, 2, 3, 4};
    public static int[] Square = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
    public static int Money = 40000;
    static ArrayList<Integer> pPos = new ArrayList<Integer>();
    void pPosList(){}

    public Board(int totalP){
        this.totalP = totalP;
    }

    public static int getPos(){
           while(Money != 0){
           for(i=0;i<Players.length;i++){ 
               System.out.println("Player Turn: Player "+(i));
               Pos = Square[roll1 + roll2];
               pPos.set(0, Pos);
               return roll1;
           }
        }
    }
}

public class Blobfish {

    public void main(String[] args) {
        System.out.println(" " +Board.getPos());
        Dice dice = new Dice();
        dice.roll1();
        dice.roll2();
        System.out.println("First Roll: " +dice.getDots1());
        System.out.println("Second Roll: " +dice.getDots2());
        System.out.println("" + dice.getSame());
        System.out.println("Your Current Position = " +Board.getPos());
    } 
}

Upvotes: 1

Views: 213

Answers (3)

Griknok
Griknok

Reputation: 386

One way to narrow down where you're going wrong is to review the structure of your classes and ask yourself how you've defined them (because they might be more complex than they need to be), and make sure you've simplified the narrowed down each of their requirements:

  • Does a 'Dice' have a limited number of rolls it can possibly do?

usually a game determine how many times you roll a dice, and how many dice you need at one time, so a single roll() function would be sufficient, and the number of Dice is determined by the class using it

  • Does a Dice remember a roll it has done in the past so you can ask it later what it once rolled? (in other words, would you roll a dice, perform some other action with the dice or even with some other part of the game you're playing, and then come back to see what the dice rolled? probably not).

the value a die supplies is immediately used by the game and stored or used by some action in the game, not by the die itself

  • If you create 100 instances of a Dice, does each have it's own Roll value, or can you roll dice24 and expect the same value to be displayed on dice81?

a hint regarding storing member values in global/static variables

Or in brief, would using the following methods not achieve something your Dice class aimed to provide?

public getRoll() {
    return number.nextInt(6) + 1;
}
public boolean compareValues(int roll1, int roll2) {
    return roll1 == roll2;
}

Bonus question: what is a dice flag?

Next lets look at the Board class: the first thing you do is store the values or Dice.roll1 and Dice.roll2, which are 0 because nothing else has happened yet, in variables that belong to Board. You can do whatever you want to the Dice class now and these two values that belong to Board can't be affected. You can dissect all the intended functionality down in a similar way as above:

  • Does an instance of a Board only get 2 Dice rolls ever?

probably not, so don't use static variables

  • Is there only one universal Board, and the game can't use another one without quitting the game and starting it up again? (otherwise all these Dice roll values are still present)

probably not, you should create an instance of Board

  • more stuff, you can dissect further

Lastly Blobfish... it looks like you are referring to the-universal-board but creating an instance of Dice which has no relation to Board, rolling them and asking Board where the players are now, which is still where they started because you are using different dice.

Write a flow of everything that would happen in real life into short sentences, then slowly turn that into Java, i.e. the game starts: each player rolls two dice, if the rolls are the same say "yay", then move the player the combined distance of the rolls

becomes:

// create the game, and a Dice for it
Board myGame = new Board();
Dice dice = new Dice();
int player = 0;

// roll the dice twice
int roll1 = dice.roll();
int roll2 = dice.roll();

// celebrate if the rolls double up
if (roll1 == roll2) {
    System.out.println("yay");
}
int distanceToMove = roll1 + roll2;

// move the player
myGame.movePlayer(player, distanceToMove);

Whenever you get stuck, simplify

Upvotes: 1

Dan
Dan

Reputation: 7724

The issue with your code is that you roll the dice but then you do not update the dice's values in the Board class

This will probably fix your problem but it does not address your layout.

public class Blobfish {

    public void main(String[] args) {
        System.out.println(" " +Board.getPos());
        Dice dice = new Dice();
        dice.roll1();
        dice.roll2();
        Board.roll1 = dice.getDots1();
        Board.roll2 = dice.getDots2();
        System.out.println("First Roll: " + dice.getDots1());
        System.out.println("Second Roll: " + dice.getDots2());
        System.out.println(dice.getSame());
        System.out.println("Your Current Position = " + Board.getPos());
    } 
}

Your code is layed out poorly. By this I mean

  • You should declare an instance of Board instead of using static variables. Ie Board b = new Board(0);
  • Not everything should be static, as variables should normally be accessed through a instance of a class unless you are using Singletons
  • Not everything should be public. Instead private variables should be used and then manipulated via Getters and Setters (In other words you want to check out encapsulation)
  • " " + someInt in System.out.println(...) is not required

An example class that implements most of what I just talked about could look like this.

public class Test {
    //Private int that can be manipulated via the use of getters and setters.
    private int someInt;

    private Test() {
        someInt = 0;
    }

    //Setter
    public void setSomeInt(int valToSet) {
        someInt = valToSet;
    }

    //Getter
    public int getSomeInt() {
        return someInt;
    }

    public static void main(String[] args) {
        //Instance of Test
        Test t = new Test();

        //Updates the value of the instance
        t.setSomeInt(10);

        //Prints the value from that same instance
        System.out.println(t.getSomeInt());
    }
}

Upvotes: 0

001
001

Reputation: 13533

I think your classes needs a slight re-design. The Board class is doing too much. Here's a rough design you might consider:

// Represents a single die
Dice
    int roll()  // Returns 1-6

// A single player. Maintains its own position on board
Player
    int getPosition()
    void move(int numSpaces)
    int bankAccount = 200

// This will contain all the spaces and whatever actions
// happen on those spaces
Board
    ?? getAction(int spaceNumber)

Bank
    payAmount(int amount)
    receiveAmout(int amount)

// The manager class. Maintains the board and players and bank
Game
    Dice dice1, dice2
    Player players[4]
    Board board
    Bank bank
    void nextTurn()
        int roll1, roll2;
        do {
            roll1 = dice1.roll()
            roll2 = dice2.roll()
            players[currentPlayer].move(roll1 + roll2)
            board.getAction(players[currentPlayer].getPosition()]
        } while roll1 == roll2
        currentPlayer = (currentPlayer + 1) % 4

There are no static variables. The Game class manages the interactions between all the other classes.

Upvotes: 0

Related Questions