0

What is really wrong with this?

    public void changeElement(String isAdd, double Element, int timesBy, int lowCap) {
    ran = Math.floor(Math.random()*timesBy)+lowCap;
    if(isAdd == "+"){
        if((Element + ran) > 100){
            ran -= ((Element + ran)-100);
        };
        Element += ran;
    }else{
        if((Element - ran) < 0){
            ran -= (ran - Element); 
        };
        Element -= ran;
    };
    Elementi = (int)Element;
    ranI = (int)ran;

}

I know the math works because i changed the 'Element' tag to the double i have been using so why does it not change the true double like its meant to.

GMYeti
  • 33
  • 7

1 Answers1

0

I presume you mean it doesn't change the value of what you pass into the parameter?

If that's the case, Java is pass by value, not pass by reference.

In other words, rather than a reference of your parameter being passed to the method, a copy of the parameter is passed. Your method changes the copy but then once the method ends, the copy goes out of scope and is garbage collected.

So what's the solution?

Change the method signature to double and return Element. Then set Element to the return value when you call your function.

Please read this relevant answer as well.

Community
  • 1
  • 1