如何在Java中从不同的类更改变量? [英] How do I change a variable from a different class in Java?

查看:335
本文介绍了如何在Java中从不同的类更改变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从另一个类中更改变量,然后在第一个类。

I'm trying to change a variable from another class, and use it back in the first class.

我在类First中创建一个变量,并赋值为1.然后我尝试在类Second中将同一变量的值更改为2,但是当我在类First中使用它时,它会变回1.

I make a variable in class First, and give it a value of 1. Then I try to change the value of the same variable to 2 in class Second, but it changes back to 1 when I use it in class First.

我是Java新手,还不知道,所以如果你

I'm new to Java and don't know very much yet, so if you could try and keep the answers simple, that would be great :)

Class First:

public class First {

    public static void main(String args[]){


    int var = 1; //Variable i'm trying to change from class "Second"

    Second Second = new Second();

    System.out.println(var); //Prints out 1

    Second.test(var); 

    System.out.println(var); // Prints out 1 again, even though I changed it

}
}



第二类:

public class Second {

    void test(int var){
    /*
     * 
     * I try to change var to 2, and it works in this class
     * but when it doesn't change in the class "First"
     * 
     */
    var = 2;
    System.out.println(var); //Prints out 2

}
}






输出结果如下:

1

2

1

1
2
1

我要取得的内容

1

2

2

1
2
2



我试图找到答案,但所有的答案,我可以找到没有对我有任何意义,因为im非常新的Java和编程。

推荐答案

问题是

Second.test(var); 

这不是一个错误。

一个原始类型( int 被称为原始类型...)它不是一个对象)传递给一个函数可以在该函数中更改,但在副本中 。一旦函数完成,原始值是相同的,因为它从未改变为以开头。

A primitive (an int is called a primitive...it's not an object) passed to a function may be changed in that function, but in a copy. As soon as the function is done, the original value is the same, because it was never altered to begin with.

你想要的是

int test(int var){
   var = 2;
   System.out.println(var); //Prints out 2
   return  var;
}

然后代替

Second.test(var); 

使用

var = Second.test(var);

实际上参数中没有任何点。它等效于

There is actually no point in the parameter at all. It is equivalent to

var = Second.test();

...

int test(){
   int var = 2;
   System.out.println(var); //Prints out 2
   return  var;
}

我希望这有助于。祝你好运,欢迎来到Java,欢迎来到stackoverflow!

I hope this helps. Good luck, welcome to Java, and welcome to stackoverflow!

这篇关于如何在Java中从不同的类更改变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆