Java 将字符串数组返回给方法并打印返回的数组
如何从方法返回Java 将字符串数组返回给方法并打印返回的数组,java,arrays,Java,Arrays,如何从方法返回字符串[]: 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方法中打印返回的字符串数组。您的代码无法编译。它有许多问题(
字符串[]
:
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方法中打印返回的字符串数组。您的代码无法编译。它有许多问题(包括语法问题) 您有语法错误-
retrun
应该是return
在demo
之后,应该有括号(如果不需要参数,则为空)
加上,String[]xs=新字符串{“a”、“b”、“c”、“d”}代码>
应该是:
String[]xs=新字符串[]{“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;
}
试试这个:
//... 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;
}
/。。。大体上
字符串[]strArr=demo();
对于(int i=0;i
你能告诉我们你是如何尝试在主屏幕上打印的吗?“因为我试过了,但没用”=>什么不起作用?你从那个方法返回了一个数组。我否决了你,因为没有证据表明你之前做过研究。你试过什么?嘿,听着,我错了,写了retrun而不是return。我在网上找到了一篇文章,我写了“return”。你看不见吗?或者String[]xs={“a”,“b”,“c”,“d”}代码>@Hitman你没有。在很短的一段时间里,我把你的问题编辑成了正确的拼写return
,然后我想我会更好。对不起,对不起..好的,但是如果我写“return”就不行了also@Hitman您编写了retrun
,有人将其编辑为return
demo
不是静态的,因此这不起作用