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

2017/3/16

Comparing images never returns True

zomoruk zomoruk

2017/3/16

#
Hello, I'm trying to compare two images and see if they are the same. However it never returns true. Can someone help me?
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
26
27
28
29
30
31
32
public void KrankenhausRadar()
    {
         
       liste = getObjectsInRange(radius,Mensch.class);
       groesse = liste.size();
              
        
           
       if (liste.size()>0 && i < liste.size())
        //(!getObjectsInRange(200, Mensch.class).isEmpty())
       {
           
            
 
           if (Greenfoot.getRandomNumber(100)<30)
           {
              Mensch mensch = getObjectsInRange(radius, Mensch.class).get(i);        
              GreenfootImage myImage;
              myImage = new GreenfootImage("immun.png");
              mensch.setImage(myImage);
              if (mensch.getImage()==img){
                  Mensch.immun = 1;
                  System.out.println("yas it works");
                }
              i=i+1;
 
             
                     
           }          
        }
         
    }
there is another class called "Mensch" which has
1
public static int immun;
in it. So I'm trying to set 'immun' to '1' whenever the object has the image 'immun.png'.
Super_Hippo Super_Hippo

2017/3/16

#
You set the image immun.png in line 20. Why do you compare the image to 'img' (whatever this is) afterwards. At this moment, you know what image currently used.
davmac davmac

2017/3/16

#
When you use "==" you are checking if two things refer to the same object, not to two objects that are the same. Because you have just set the image (line 28) to a new image object, there is no way that this can now be the same image object as the pre-existing 'img'. You could compare the images using the .equals(...) method, something like:
1
if (mensch.getImage().equals(img)){
And this might work as you want, but it also might not: exactly how GreenfootImage compares for image equality is not formally specified. Even if it does work, it will not be efficient: it will have to compare every pixel of each image. It would be far better to create, set and compare a variable of primitive type which you control directly, rather than trying to compare two images. For instance, in the Mensch class, you can add a boolean variable which you can set to true whenever you set its image to the special image that you are looking for. Then you can just check this variable rather than comparing the images.
You need to login to post a reply.