2017-05-07 22 views
0

有人可以告訴我如何獲得方法內的變量和相反。 類似於: 我想在該方法func中使用變量y,並從該方法func獲取該x並在main中使用它。Java我怎樣才能得到一個方法內的變量和相反

class test{ 
int y = 4; 

void func(){ 
int x = 3; 
} 

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

的FUNC鍵更改簽名,使它return int – Oscar

+0

你可以在func外使用x,因爲這是函數的本地屬性。如果你想在主函數中使用。使其成爲類的靜態變量。 – Vikrant

+0

使func靜態或創建類測試的實例,然後調用func返回x –

回答

0
class test{ 
int y = 4; 

int func(){ 
    int x = 3; 
    return x; 
} 

public static void main(String[] args) 
{ 
    test obj = new test(); 
    int x = obj.func(); 
    } 
} 

,或者你可以讓FUNC()方法,靜態,你將能夠調用此方法,而無需創建類的一個對象:

class test{ 
int y = 4; 

static int func(){ 
    int x = 3; 
    return x; 
} 

public static void main(String[] args) 
{ 

    int x = func(); 
    } 
} 
0
class test{ 
    int y = 4; 
    int x; 

    void func(){ 
     int x = 3; 
     this.x = 3; //make it usable from the class 
    } 
} 

Ÿ應該可以訪問內部功能。如果函數本身使用變量y,則可以使用this.y來訪問該變量。

使它像這樣靜態可以讓你通過調用test.y來訪問它。

class test{ 
    public static int y = 4; 

    void func(){ 
     int x = 3; 
    } 
} 

然後你可以在main中做到這一點。

public static void main(String[] args) 
{ 
    int value = test.y; 
} 
0

嘗試是這樣的:

class Main { 
    public int y= 4; 
    int func(){ 
    return 4; 
    } 
    public static void main(String... args){ 
    Main m = new Main(); 
    int x = m.func(); 
    int y = m.y; 

} 
} 
1

您可以隨時使用內部方法類變量。要使用內部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 
相關問題