gpt4 book ai didi

java - java中如何将字符串值从子方法传递到主方法?

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

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";
}
}

如何打印我的名字?运行该程序时出现初始化错误。

最佳答案

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

关于java - java中如何将字符串值从子方法传递到主方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22779456/

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