2017-06-13 54 views
-4
package Student; 

public class Example 
{ 
    int i = 10;//instance variable which is created under class 

    void age()// age is method here 
    { 
     int j=11;// local variable which is created under method 

} 

    public static void main(String[] args) { 


     Example ex = new Example();//Creating the object 
     System.out.println("Display the valule" ex.age()); 


     ex.age(); 

    } 
} 

我無法打印第j值的價值..打印局部變量

+4

Java教程:從方法返回一個值(https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html) – khelwood

+0

你需要從返回''j' age'。另外,你需要說出你在問什麼時遇到了什麼問題。這是一個非常模糊的問題 – Carcigenicate

回答

0

您需要返回j所以你的功能應該是這樣的:

int age()// age is method here 
{ 
     int j=11; 
     return j; // return j 
} 
1

系統.out.println(「顯示值」+ ex.age());

你期待上面的行打印年齡,但它不會因爲你的年齡方法沒有返回任何東西。

試試這個:

int age()// Now your age method will return an integer value 
{ 
     int j=11;// local variable which is created under method 
     return j; 
} 
+0

你需要sysout的加號 – Isac

+0

@Isac感謝您指出 –

0

你必須寫一個返回方法變量

public int getAge() 
{ 
    return age; 
} 

,然後使用ex.getAge()的年齡

0

的系統輸出將打印任何傳入的值。方法age()沒有返回任何值。應該修改age()方法以使返回類型爲int,並返回變量j而不是僅設置該值。您通常應該使用getter和setter,如下所示,並調用set方法並使用get方法在sysout中進行打印。

void setAge() { 
j = 11; 
} 

int getAge() { 
    return j; 
}