2013-12-18 3 views
0

// Как вернуть массив в Java?Как вернуть массив в Java?

public class Song2 { 
      String name; 
      String artist; 
      String genre; 
      String year; 

      public void intro(){ 
      System.out.println("Welcome to the song!"); 
      } 

      public void verse(){ 
      System.out.println("Let's take you to a verse"); 
      } 

      public void chorus() 
      System.out.println("And now how about a chorus?"); 
      } 

      public void end(){ 
      System.out.println("Here's the end of the song"); 
      } 

    } 

//this is my array. 
    import javax.swing.JOptionPane; 
    public class SongTestDrive2 
    { 
     public static void main(String[] args) 
     { 

      Song2[] mySong2 = new Song2[2]; 
      int x = 0; 
      mySong2[0] = new Song2(); 
      mySong2[1] = new Song2(); 
      mySong2[0].name = "Song Title: soul to squeeze"; 
      mySong2[1].name = "Song Title: Slaughtered"; 
      mySong2[0].artist = "Artist: Red Hot Chili Peppers"; 
      mySong2[1].artist = "Artist: PanterA"; 
      mySong2[0].genre = "Genre: Funk Rock"; 
      mySong2[1].genre = "Genre: Groove Metal"; 
      mySong2[0].year = "Year: 1993"; 
      mySong2[1].year = "Year: 1994"; 
      } 

    } 
+4

Мне очень жаль, что точный массив и что вы возвращающие его? Потому что вы его создаете в основном. –

+0

что это именно ваша проблема? – Gustavo

+0

В чем ваш вопрос? – Alex

ответ

1

Я не понимаю, что ваш вопрос, так что я просто ответить на то, что кажется уместным основано на том, что вы написали, и что вы, кажется, хотят сделать.

private String[] myMethod() { 
    String[] myArr = {"1", "2", "3"}; 
    return myArr; 
} 

Так метод возвращает массив.

Чтобы передать массив методу в качестве аргумента просто указать, что метод принимает массив в качестве аргумента

private void myMethod(String[] data) { 
    System.out.println(data[0]); 
} 
+0

Yup. Но дело в том, что OP не вызывает метод. Можете ли вы добавить пример кода, чтобы ОП понимал, что ему нужно вызвать метод из main, чтобы «возвратить» что-то. –

0

Это просто тип возврата:

public Song[] getSongs() { 
    // populate an array of songs. 
    // This is a basic implementation that loads data statically. 
    Song2[] mySong2 = new Song2[2]; 
    mySong2[0] = new Song2(); 
    mySong2[1] = new Song2(); 
    mySong2[0].name = "Song Title: soul to squeeze"; 
    mySong2[1].name = "Song Title: Slaughtered"; 
    mySong2[0].artist = "Artist: Red Hot Chili Peppers"; 
    mySong2[1].artist = "Artist: PanterA"; 
    mySong2[0].genre = "Genre: Funk Rock"; 
    mySong2[1].genre = "Genre: Groove Metal"; 
    mySong2[0].year = "Year: 1993"; 
    mySong2[1].year = "Year: 1994"; 
} 

Предполагая, что это в ваш SongTestDrive2 класс, в главном:

public static void main(String[] args) { 
    Song [] songs = getSongs(); 
} 

следующая задача состоит в том, чтобы загрузить песни л ist откуда-то более всеобъемлющим, как база данных или файл. Эта задача будет очень специфичной для вашего источника данных.

0

Здесь вы идете, совершенно разумный и способный работать полный код.

package try1; 
import try1.Song; 

public class Main { 

public static void main(String[] args){ 
    //creates a Song Array and calls the addTwoSongs method to fill the mySongs array 
    Song[] mySongs = addTwoSongs(); 
    //prints some stuff of the existing objects in the array 
    mySongs[0].printintro(); 
    mySongs[0].printchorus(); 
    mySongs[1].printverse(); 
    mySongs[1].printend(); 
} 

public static Song[] addTwoSongs(){ 
    //creates new Song Array to save two Songs 
    Song[] tmpSongs = new Song[2]; 
    //creates two new Songs and adds to the array 
    tmpSongs[0] = new Song("soul to squeeze", "Red Hot Chili Peppers", "Funk Rock", "1993"); 
    tmpSongs[1] = new Song("Slaughtered", "PanterA", "Groove Metal", "1994"); 
    //returns the array 
    return tmpSongs; 
} 
} 

два класса, один основной и объект Song

package try1; 

public class Song { 
String name; 
String artist; 
String genre; 
String year; 

//Constructor to set all attributes with init of object 
public Song(String tmpName, String tmpArtist, String tmpGenre, String tmpYear){ 
    this.name=tmpName; 
    this.genre=tmpGenre; 
    this.artist=tmpArtist; 
    this.year=tmpYear; 
} 
//empty Constructor 
public Song(){ 

} 

public void printintro(){ 
    System.out.println("Welcome to the song!"); 
} 

public void printverse(){ 
    System.out.println("Let's take you to a verse"); 
} 

public void printchorus(){ 
    System.out.println("And now how about a chorus?"); 
} 

public void printend(){ 
    System.out.println("Here's the end of the song"); 
} 

} 
Смежные вопросы