Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将字符串数组返回给方法并打印返回的数组_Java_Arrays - Fatal编程技术网

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
不是静态的,因此这不起作用