首页 > 解决方案 > 调用两个方法并将调用第一个方法的结果传递给第二个方法的主方法

问题描述

我的任务是创建一个调用两个方法的主方法。第一种方法返回字符串数组,而第二种方法获取字符串数组并在单独的行上打印出元素。然后 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); 
  } 
}

标签: javafunctionmethods

解决方案


您的代码有效,但在 中main, 的返回值method1被忽略。而且不需要打电话method1method2

您可以让method2接受参数String[] strings

public static void method2(String[] strings) {

    for (String str : strings)
        System.out.println(str);
}

并将结果传递method1method2

String[] result = method1();
method2(result);//Will print the strings in the array that

推荐阅读