samedi 16 mars 2019

Why is my random index selector returning the attribute's location in the memory in Java? [duplicate]

This question already has an answer here:

So for some reason, when I'm programming this diceThrow method of mine, it seems to be outputting the location of the ArrayList's item in the memory, rather than the value of that item itself. I'm not sure why this is the case, please can someone, assist.

P.S. I am aware that there's a much easier way to write a dice throwing program, however, my university wants us to get familiar with ArrayLists and classes etc.

package dicesystem;

public class DiceSide {

    private String side;

    public DiceSide(String side){
        this.side = side;

    }

    public String getSide(){
        return this.side;
    }
}

package dicesystem;

import java.util.ArrayList;

public class Dice {

    private ArrayList<DiceSide> Sides;

    public Dice(){
        this.Sides = new ArrayList<DiceSide>();
    }

    public void addSide(String side){
        DiceSide newDiceSide = new DiceSide(side);
        Sides.add(newDiceSide);
    }

    public String diceThrow(){
        int randomIndex = (int) (Math.random() * Sides.size());
        System.out.println("Dice Output: " + Sides.get(randomIndex));
        return "1";
    }
}

package dicesystem;

public class DiceTest {

    public static void main(String []args){
        Dice dice = new Dice();
        dice.addSide("1");
        dice.addSide("2");
        dice.addSide("3");
        dice.addSide("4");
        dice.addSide("5");
        dice.addSide("6");

        dice.diceThrow();
        dice.diceThrow();
        dice.diceThrow();
        dice.diceThrow();
        dice.diceThrow();
    }
}

The outputted results of this are:

Dice Output: dicesystem.DiceSide@4554617c

Dice Output: dicesystem.DiceSide@74a14482

Dice Output: dicesystem.DiceSide@1540e19d

Dice Output: dicesystem.DiceSide@677327b6

Dice Output: dicesystem.DiceSide@14ae5a5

Any and all assistance is much appreciated :D




Aucun commentaire:

Enregistrer un commentaire