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

2016/3/16

Images not equal (possible bug)

DogeOverlord DogeOverlord

2016/3/16

#
So I have the following code:
1
2
3
4
5
6
7
8
9
10
11
public void change(){
        setImage("tecup.png");
        if(getImage() == new GreenfootImage("tecup.png")){
            setLocation(25, 15);
            setImage("tecup.png");
        }
        else{
            setLocation(75, 25);
            setImage(new GreenfootImage("Made by TeaNCode, Copyright 2016", 12, Color.WHITE, new Color(0,0,0,0)));
        }
    }
and when run it always executes the setImage "Made by TeaNCode" instead of the setImage "tecup.png", which I believe to be a bug. The initial setImage is just to ensure that this is the issue is being caused by that if statement. I have the latest version of Greenfoot.
danpost danpost

2016/3/17

#
That is not a bug. Take the following code:
1
2
String stringA = new String("abcde");
String string = new String("abcde");
Each line creates a separate instance of a String object. The two objects are not one in the same, but different objects. They are not stored in memory at the same location (they have different memory addresses -- which is what is actually being compared when comparing Object references). The two strings are similar, in that their contents are the same. You can compare the contents of two similar type objects using the 'equals' method of the Object class (which is overridden in classes where content can be compared):
1
2
String stringA = new String("abcde");
System.out.println(new String("abcde").equals(stringA));
Here, the Sting object created in the second line is not the same String object as 'stringA'; but, since their inner content are equal, 'true' will output.
DogeOverlord DogeOverlord

2016/3/17

#
I tried
1
if(getImage().equals(new GreenfootImage("tecup.png")))
which didn't work but I found another way to do it so it is ok.
danpost danpost

2016/3/18

#
Maybe the best way is to have an instance reference field to hold the image, set the image of the actor to it, then you can check the image of the actor with the field value as being the same object (using '==').
You need to login to post a reply.