2014-04-01 54 views
0
public class NewTest { 
    @Test 
    public static void main(String [] args) throws IOException { 
     new NewTest(); 
     NewTest.test(); 
     System.out.println(myname); 
    } 
    public static void test(){ 
     String myname = "Sivarajan"; 
    } 
} 

如何打印myname?運行此程序時出現初始化錯誤。如何將字符串值從子方法傳遞給java中的main方法?

+0

通過閱讀教程:http://docs.oracle .com/javase/tutorial/java/javaOO/index.html –

+0

由於'myname'是在'test()'內聲明並初始化的,所以你不能在別處訪問它。如果你想在其他地方使用這個變量,你可以把它定義爲一個類變量。 – csmckelvey

+0

@tsivarajan請提供一些關於提供的答案的反饋,以便我們可以看到這個問題是否得到解決。 – csmckelvey

回答

0

Java變量有不同的範圍。如果你在一個方法中定義一個變量,那麼它在另一個方法中是不可用的。

的方式來解決它在你的代碼:

1把這些變量作爲成員類

public class NewTest { 

    public static String myname = "Sivarajan"; 

    @Test 
    public static void main(String [] args) throws IOException 
    { 
     /*Note that since you are working with static methods 
     and variables you don't have to instantiate any class*/ 
     System.out.println(myname); 
    } 

2進行test返回一個字符串

public class NewTest { 

    @Test 
    public static void main(String [] args) throws IOException 
    { 
     NewTest newt = new NewTest(); 
     System.out.println(newt.test()); 
    } 

    //Note that we did remove the static modifier 
    public String test(){ 
     String myname = "Sivarajan"; 
     return myName; 
     //or simply return "Sivarajan"; 
    } 
} 

延伸閱讀:

http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html

http://java.about.com/od/s/g/Scope.htm

+0

你的第二個解決方案目前不會編譯,你的方法說它返回一個String類型,但你只創建了一個新的變量,沒有返回它。 – Levenal

+0

@Levenal你是對的。固定,謝謝;) – Averroes

+0

我同意你的觀點@Averroes – tsivarajan

0

因爲你的變量myname聲明和test()方法裏面初始化,它是在你的程序無法使用其他任何地方。你可以有test()方法返回一個像這樣的字符串:

public class NewTest { 
    @Test 
    public static void main(String [] args) throws IOException { 
     new NewTest(); 
     NewTest.test(); 
     System.out.println(test()); 
    } 
    public static String test() { //Changed to return a String 
     return "Sivarajan"; 
    } 
} 

或聲明爲一個類變量,然後用它在類的所有方法之後

public class NewTest { 
    String myname = "Sivarajan"; //added myname as a class variable 

    @Test 
    public static void main(String [] args) throws IOException { 
     new NewTest(); 
     NewTest.test(); 
     System.out.println(myname); 
    } 
} 
+0

我試圖將子方法的值傳遞給main方法。 @Takendarkk – tsivarajan

0

我知道你在想實現涉及使用對象的「字段」。你所做的是在一個方法中聲明一個變量,這意味着它只能在該方法中被引用。通過聲明一個字段,然後你可以創建你的類的對象,並且每個人都可以訪問該字段,如下所示:

public class NewTest { 
     public static void main(String [] args) { 
     //Create NewTest object 
     NewTest tester = new NewTest(); 

     //Run the method on our new Object 
     tester.test(); 

     //Print the field which we just set 
     System.out.println(tester.myName); 
     } 

     //Set the field 
     public void test(){ 
     myName = "Sivarajan"; 
     } 

    //A public field which is accessible in any NewTest object that you create 
    public String myName = ""; 
    } 
相關問題