This site requires JavaScript, please enable it in your browser!
Greenfoot back
xxX_Muffin.man_Xxx
xxX_Muffin.man_Xxx wrote ...

2014/11/18

Confused

xxX_Muffin.man_Xxx xxX_Muffin.man_Xxx

2014/11/18

#
Im trying to do this Snakes and ladders type board game and Im trying to get a dice that generates a number and says "(player1) rolled = (random number)" Theres another world that is like a name choosing menu (changename) where I put a string, String name1 = "default name" The player supposedly chooses a name if they want and the name will appear with the value of the dice rolled. The dice is in another world which is the game. This is a function in the changename world
  public String getName1()
    {
        return name1;

    }

    public void setName1(String x)
    {
        name1 = x;        
    }
This code works in the 'changename' world however when I use getName1() in the 'game' world it says java.lang.ClassCastException: game cannot be cast to changename at dice.act(dice.java:17) at greenfoot.core.Simulation.actActor(Simulation.java:568) at greenfoot.core.Simulation.runOneLoop(Simulation.java:526) at greenfoot.core.Simulation.runContent(Simulation.java:215) at greenfoot.core.Simulation.run(Simulation.java:205) No clue what ive done wrong.
public void act() 
    {
        // Add your action code here
        changename worldref1 = (changename) getWorld();
        String Name1 = worldref1.getName1();
        
}
davmac davmac

2014/11/18

#
java.lang.ClassCastException: game cannot be cast to changename
This means that you've taken the current world, which is of type 'game', and tried to cast it to 'changename'. I think the problem line is probably this one:
        changename worldref1 = (changename) getWorld(); 
You can't just cast the world to 'changename' if it is not actually a changename instance. If you want to refer to the 'changename' world, you need to maintain a reference to it in a variable. Also, Java convention is to have class names begin with capitals. It should be 'Game' and "ChangeName', not 'game' and 'changename'. Using these names is confusing for other people (like me) who read your code and expect a name like 'game' to be a variable, not a class.
danpost danpost

2014/11/18

#
'getWorld' in your act method is returning the world your actor is in, not the 'changename' world from which you are trying to access the 'getName1' method. You probably need to keep a reference to the 'changename' world or make the name fields and the methods in the 'changename' world 'static', so you can access the methods through the class name:
You need to login to post a reply.