将字符串数组返回给方法并打印返回的数组

时间:2013-03-12 11:40:15

标签: java arrays

如何从方法中返回string[]

public String[] demo
{
  String[] xs = new String {"a","b","c","d"};
  String[] ret = new String[4];
  ret[0]=xs[0];
  ret[1]=xs[1];
  ret[2]=xs[2];
  ret[3]=xs[3];

  retrun ret;
}

这是对的,因为我尝试过它并没有用。如何在main方法中打印此返回的字符串数组。

2 个答案:

答案 0 :(得分:5)

您的代码无法编译。它遇到很多问题(包括语法问题)。

您有语法错误 - retrun应为return

demo之后你应该有括号(如果你不需要参数,则为空)

另外,String[] xs = new String {"a","b","c","d"};

应该是:

String[] xs = new String[] {"a","b","c","d"};

您的代码应如下所示:

public String[] demo()  //Added ()
{
     String[] xs = new String[] {"a","b","c","d"}; //added []
     String[] ret = new String[4];
     ret[0]=xs[0];
     ret[1]=xs[1];
     ret[2]=xs[2];
     ret[3]=xs[3];
     return ret;
}

把它放在一起:

public static void main(String args[]) 
{
    String[] res = demo();
    for(String str : res)
        System.out.println(str);  //Will print the strings in the array that
}                                 //was returned from the method demo()


public static String[] demo() //for the sake of example, I made it static.
{
     String[] xs = new String[] {"a","b","c","d"};
     String[] ret = new String[4];
     ret[0]=xs[0];
     ret[1]=xs[1];
     ret[2]=xs[2];
     ret[3]=xs[3];
     return ret;
 }

答案 1 :(得分:0)

试试这个:

//... in main
String [] strArr = demo();
for ( int i = 0; i < strArr.length; i++) {
    System.out.println(strArr[i]);
}

//... demo method
public static String[] demo()
{
    String[] xs = new String [] {"a","b","c","d"};
    return xs;
}