-1

如何string[]从方法返回 a:

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 方法中打印这个返回的字符串数组。

4

2 回答 2

9

Your code won't compile. It suffers from many problems (including syntax problems).

You have syntax errors - retrun should be return.

After demo you should have parenthesis (empty if you don't need parameters)

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

should be:

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

Your code should look something like this:

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

Put it together:

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;
 }
于 2013-03-12T11:42:09.700 回答
0

try this:

//... 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;
}
于 2013-03-12T11:44:18.187 回答