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

2016/4/5

How can I modify an "int" from another Class?

madeirense madeirense

2016/4/5

#
Inside the "Ship" Class
1
public int PUP = 1;
1
2
3
4
5
6
7
if(Greenfoot.isKeyDown("space"))
        {           
            if(PUP == 1)
           { Will shoot only 1 bullet at a time }
            if(PUP == 2)
           { Will shoot 3 bullets at a time }
        }
Anyway, what I want to do is then in the "PowerUP" class change the value from 1 to 2, 3, 4,... According to how many PowerUPs I've already gathered. I've tried this:
1
2
3
4
5
6
7
8
Actor MiniPowerUP = getOneIntersectingObject(Ship.class);
         
        if (MiniPowerUP != null) {
            Greenfoot.playSound("explosion.wav");
            ((AsteroidWorld)(getWorld())).score.add(50);
            getWorld().removeObject(this);
            int PUP = ((Ship)getWorld().getObjects(Ship.class).get(0)).PUP++;
        }
but Greenfoot crashes in " int PUP = ((Ship)getWorld().getObjects(Ship.class).get(0)).PUP++;" whenever I try to "catch" a PowerUP
danpost danpost

2016/4/5

#
The right side of the assignment statement at line 7 (the line in question) does not represent a value. It, the right side, is an execution statement that increments the value of PUP in the Ship object referenced. In other words, you do not need the 'int PUP =' part of the line for the value to be modified when using '++'. It is already presumed that the variable named is what gets incremented. You would use the 'int PUP =' part to create a local field within the method to hold the new value. However, you would have to modify it using an assignment statement something like this:
1
int PUP = (((Ship)getWorld().getObjects(Ship.class).get(0)).PUP += 1);
The value of PUP in the Ship object is incremented, and its value only will be assigned to the new local variable 'PUP'. Any further changes to the local variable will not modify the PUP field in the Ship object.
madeirense madeirense

2016/4/5

#
Still crashing, java.lang.NullPointerException at PowerUP.act(PowerUP.java:44)
1
int PUP = (((Ship)getWorld().getObjects(Ship.class).get(0)).PUP += 1);
"The value of PUP in the Ship object is incremented, and its value only will be assigned to the new local variable 'PUP'. Any further changes to the local variable will not modify the PUP field in the Ship object." Okay, it's best to put my question like this, how do I change the value from a variable that isn't present in the same Actor?
danpost danpost

2016/4/5

#
madeirense wrote...
Still crashing, java.lang.NullPointerException at PowerUP.act(PowerUP.java:44)
Switch lines 6 and adjusted line 7 above (remove the powerup from the world after adjusting the value of PUP).
You need to login to post a reply.