gpt4 book ai didi

Java如何获取方法内的变量以及相反的情况

转载 作者:行者123 更新时间:2023-12-02 13:14:16 25 4
gpt4 key购买 nike

有人可以告诉我如何在方法内部获取变量,反之亦然。就像是:我想在该方法 func 中使用变量 y,并从该方法 func 中获取 x 并在 main 中使用它。

class test{
int y = 4;

void func(){
int x = 3;
}

public static void main(String[] args)
{
// take x inside main
}}

最佳答案

您始终可以在方法内使用类变量。要在 main() 方法中使用 func() 的 x,您可以从 func() 返回它或将其保存到某个类变量中

class TestClass {
int y = 4;
int x = 0;

//func returning x
int func1() {
int x = y;
return x;
}

//func storing it to class variable
void func2() {
this.x = 3;
}

public static void main(String[] args) {
TestClass t = new TestClass();
int xOfFunc = t.func1();

t.func2();
System.out.println("x Of Func :: " + xOfFunc + "\n class variable x :: " + t.x);
}
}

输出:

x Of Func :: 4 
class variable x :: 3

关于Java如何获取方法内的变量以及相反的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43836057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com