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

試してみてうまくいかなかったので、これは正しいですか?この返された文字列配列をメイン メソッドで出力するにはどうすればよいですか。

4

2 に答える 2

9

コードはコンパイルされません。それは多くの問題(構文の問題を含む)に悩まされています。

構文エラーがあります-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;
 }
于 2013-03-12T11:42:09.700 に答える
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;
}
于 2013-03-12T11:44:18.187 に答える