[英]How to pass String value from sub method to main method in 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
? 運行該程序時出現初始化錯誤。
Java變量具有不同的作用域 。 如果在方法內定義變量,則該變量在另一個方法內不可用。
在代碼中修復它的方法:
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);
}
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
因為您的變量myname
是在test()
方法內部聲明和初始化的,所以它在程序中的其他任何地方都不可用。 您可以讓test()
方法返回如下所示的String:
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);
}
}
我認為您要實現的目標涉及使用對象的“字段”。 您所做的一切都在方法內部聲明為變量,這意味着只能在該方法內部引用它。 通過聲明一個字段,您可以創建類的對象,每個對象都可以訪問該字段,如下所示:
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 = "";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.