2つのメソッドを呼び出して、第二の方法に上の最初のメソッドを呼び出した結果を渡しMainメソッド

suppko:

私は2つのメソッドを呼び出すmainメソッドを作成する使命を帯びています。第2の方法は、文字列の配列を取得し、別の行に要素を印刷しつつ、第1の方法は、文字列の配列を返します。主な方法は、次に、第2の及び停止する最初のメソッドを呼び出した結果を渡します。私は正しく質問を理解し、それをやっていますか?私はコンパイルして実行すると、私は取得します

sunshine
road
73
11

public class Hihihi
{

public static void main(String args[]) 
{
  method1();
  method2();//Will print the strings in the array that
            //was returned from the method1()
   System.exit(0); 
}                                 



public static String[] method1() 
{
     String[] xs = new String[] {"sunshine","road","73","11"};
     String[] test = new String[4];
     test[0]=xs[0];
     test[1]=xs[1];
     test[2]=xs[2];
     test[3]=xs[3];
     return test;
 }

   public static void  method2()
  { 
    String[] test = method1();
    for(String str : test)
        System.out.println(str); 
  } 
}
Stultuske:

最初に、あなたのを修正 method2

これは、アレイ受け入れることができなければならないStringパラメータなどの要素を:

public static void  method2(String[] test)
  { 
    // this line is not needed -> String[] test = method1();
    for(String str : test)
        System.out.println(str); 
  } 

このように、あなたが実際にあなたの要件が説明するように、メソッドにデータを渡します。ボーナスは次のとおりです。他のためのそれの再利用可能なStringだけでなく、配列。

あなたはmethod1冗長なコードの多くを持っています。ちょうどそのうちにフィルタを適用

public static String[] method1() 
{
     return new String[] {"sunshine","road","73","11"};
}

そして今、あなたのmain方法は、単にそれらをリンクします。変化する

public static void main(String args[]) 
{
  method1();
  method2(); // this will now cause a compilation error, because it expects a parameter
   System.exit(0); 
} 

に:

public static void main(String args[]) 
{      
  method2(method1());
   System.exit(0); 
} 

コードが最初に構築された方法は、method1最初に、2回呼ばれたmain第二の時間、結果は使用しなかったので、完全に冗長であった方法、method2データが通過しなければならないので、それは、呼び出されるべきではない場合、パラメータとして。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=197553&siteId=1