我的任务是创建一个调用两个方法的主要方法。第一种方法返回字符串数组,而第二种方法获取字符串数组并在不同的行上打印出元素。然后 main 方法将调用第一个方法的结果传递给第二个方法,然后停止。我这样做是否正确理解了问题?当我编译并执行时,我得到
sunshine
road
73
11
public class Hihihi
{
public static void main(String args[])
{
method1();
method2();//Will print the strings in the array that
//was returned from the method1()
System.exit(0);
}
public static String[] method1()
{
String[] xs = new String[] {"sunshine","road","73","11"};
String[] test = new String[4];
test[0]=xs[0];
test[1]=xs[1];
test[2]=xs[2];
test[3]=xs[3];
return test;
}
public static void method2()
{
String[] test = method1();
for(String str : test)
System.out.println(str);
}
}
最佳答案
首先,修正你的method2
它必须能够接受一个 String
元素数组作为参数:
public static void method2(String[] test)
{
// this line is not needed -> String[] test = method1();
for(String str : test)
System.out.println(str);
}
这样,您实际上按照您的要求将数据传递给方法。一个好处是:它也可重复用于其他 String
数组。
您的method1
有很多冗余代码。把它过滤掉
public static String[] method1()
{
return new String[] {"sunshine","road","73","11"};
}
现在,您的 main
方法只是为了链接它们。变化
public static void main(String args[])
{
method1();
method2(); // this will now cause a compilation error, because it expects a parameter
System.exit(0);
}
到:
public static void main(String args[])
{
method2(method1());
System.exit(0);
}
您的代码最初构建的方式,method1
被调用了两次,第一次是在 main
方法中,这是完全多余的,因为没有使用结果,第二次在 method2
中,不应调用它,因为数据应作为参数传递。
关于java - 调用两个方法并将调用第一个方法的结果传递给第二个方法的主方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52094380/