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

2022/2/21

Checking if 2 Strings are equal

Kwantum Kwantum

2022/2/21

#
For my code, I need to be able to check if a string is equal to a string from another class (Minion).
public Things()
    {
        setImage(blank);
        GreenfootImage image = getImage();
        image.scale(image.getWidth() - 250, image.getHeight() - 250);
        setImage(image);
        
        
        
    }
    public void act()
    {
        System.out.println(Minion.chunk);
        //System.out.println(Minion.chunk.equals("0/0"));
        
        
    }
When I run this code, the Terminal keeps saying: 0/0 But when I remove the commenting:
public Things()
    {
        setImage(blank);
        GreenfootImage image = getImage();
        image.scale(image.getWidth() - 250, image.getHeight() - 250);
        setImage(image);
        
        
        
    }
    public void act()
    {
        System.out.println(Minion.chunk);
        System.out.println(Minion.chunk.equals("0/0"));
        
        
    }
The terminal says: null one and then the games stops. What is going on?
Kwantum Kwantum

2022/2/21

#
Extra context: chunk is static and Minion and Things are not each others subclasses or superclasses.
RcCookie RcCookie

2022/2/21

#
You can replace
Minion.chunk.equals("0/0")
with
"0/0".equals(Minion.chunk)
or with the two-way null safe
import java.util.Objects;
// ...
Objects.equals(Minions.chunk, "0/0")
although that does not really solve the main problem. Clearly the value of chunk is "0/0" in the first and null in the second output. Trying to call "equals" on the value null then produces a NullPointerException. One thing that could cause this is that chunk has initially the value null and gets set to "0/0" later on. Clear the output and run version 1 again, and check the very first output. It may be null, and the second version does not pass that point because of the exception.
Kwantum Kwantum

2022/2/22

#
Ah, thanks. This helped me understand the problem and I managed to fix it!
You need to login to post a reply.