简体   繁体   中英

Setting a value to zero

Ok so in my cs class we have an assignment that requires us to return a value and then set it to zero. I can't figure out how to do this without using a secondary variable(which would break requirements) so I would appreciate some help. here are the exact requirements.

"Has a use() method that returns the value contained in the points field. It also resets the points field to zero. You're going to have to think about the order of operations here to make this work correctly."

package Game;

import java.util.Random;

public class HealthPotion 
{
    private int points;
    boolean Haspotion;
    HealthPotion()
    {
        Random num1 = new Random();
        int num = num1.nextInt(10)+1;
        points=num*10;
    }
    public int Use()
    {
        return points;
    }
    public int getPoints() 
    {
        return points;
    }
}

That's not really possible without abusing a finally block, ie

try {
    return points;
} finally {
    points = 0;
}

However it's really hard to believe that would be what's wanted, since it's not a good idea to write code like that.

Include a setter method like this.

public void setValue(){
this.points=0;
}

Call this method after you get the value.

How about this?

public int Use() 
    {
        int tmp =  points;
        points = 0;
        return tmp;
    }

It has limitations, especially if points can be changed by a different thread while this method executes. But if you are working in a single-threaded environment this should be ok.

This should work

int points = 5;

public void test(){
    System.out.println(use() +" " + points);

}

private int use(){
    return points - (points = 0);
}

returning 5 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM