简体   繁体   English

Java使用方法添加到整数

[英]Java adding to an integer using methods

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 任何有关如何使其工作的提示是最受欢迎的

In Java, int is passed by value. 在Java中, int按值传递。 If you want to add you should return the value and reassign it. 如果要add ,则应返回值并重新分配。

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

Then, to call it, 然后,打电话给它,

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

What happens is that Java is always pass-by-value . 会发生什么是Java 总是按值传递 So, in your example, if you modify the integer val inside the method, it won't have effect outside. 因此,在您的示例中,如果您修改方法内的整数val ,它将不会在外部生效。

What can you do? 你能做什么?

You can declare your method to return an integer , then you assign the result to the variable you want: 您可以声明方法返回一个integer ,然后将结果分配给您想要的变量:

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'

你应该在你的thing类中有一个私有的int val,否则在你的add()方法中添加“return”语句并在返回的调用位置设置返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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