如何在java中将String值从sub方法传递给main方法?

时间:2014-04-01 07:31:23

标签: java

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?运行此程序时出现初始化错误。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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); 
    }
}

答案 2 :(得分: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 = "";
  }
相关问题