Domanda

I am having trouble with a relatively simple problem: I am trying to use a method from another class to add to an integer in my main class but the value of my integer is not increasing, the value stays the same, this is what the code looks like:

public class prog{

/**
 * @param args
 * @throws MidiUnavailableException 
 */

public static void main(String[] args) {
int num = 11;
thing.add(num);
System.out.println(num);
}
}

and the class 'thing' being:

public class chords2 {

static void add(int val){
    val = val+9;

}

}

any tips on how to get this to work is most appreciated

È stato utile?

Soluzione

In Java, int is passed by value. If you want to add you should return the value and reassign it.

static int add(int val){
    return val+9;
}

Then, to call it,

int num = 11;
num = thing.add(num);

Altri suggerimenti

What happens is that Java is always pass-by-value. So, in your example, if you modify the integer val inside the method, it won't have effect outside.

What can you do?

You can declare your method to return an integer, then you assign the result to the variable you want:

static int add(int val){
    return val + 9;    
}

and when you call it:

int num = 11;
num = SomeClass.add(num); // assign the result to 'num'

You should have a private int val in your thing class, otherwise add "return" statement to your add() method and set the return value back in calling position.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top