2013-03-12 78 views
-4

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

+3

,你能告诉我们你是如何在你的主要尝试打印? – duffy356 2013-03-12 11:41:23

+3

“*因为我试过了,它力度不够*”=>什么都不起作用?你*从这个方法返回一个数组。 – assylias 2013-03-12 11:41:30

+3

我已经低估了你,因为你没有任何证据证明你有过预研究。 *你*尝试过什么? – 2013-03-12 11:41:44

回答

4

你的代码不会编译。它遭受很多问题(包括语法问题)。

您有语法错误 - 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; 
} 
+0

嘿,我没有写“回报”..不能你看? – Hitman 2013-03-12 11:44:56

+2

或'String [] xs = {“a”,“b”,“c”,“d”};' – assylias 2013-03-12 11:45:08

+2

@Hitman您没有。在短短的一段时间里,我编辑了你的问题来正确拼写'return',然后我想到了更好。 – 2013-03-12 11:46:00

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

'demo'不是静态的,所以这不起作用 – 2013-03-12 11:46:35