2013-12-19 35 views
0

我正在嘗試將數組傳遞給方法。我在編譯時不斷收到錯誤,錯誤是「找不到符號songArray」。將數組傳遞給方法,遇到錯誤是「找不到符號songArray」

SongTestDrive

import javax.swing.JOptionPane; 
public class SongTestDrive { 
    public static void main(String[] args) { 

     String[] Song = { "Song title: soul to squeeze", "Artist: Red Hot Chili Peppers", "Genre: Funk Rock", "Year: 1993", "Song title: Slaughtered", 
       "Artist: PanterA", "Genre: Groove Metal", "Year: 1994" }; 

     songArray(); //<--- Im having issues right here// 
    } 
} 

import javax.swing.JOptionPane; 

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

    public void songArray(String[] Song) { 
     for (String o : Song) { 
      JOptionPane.showMessageDialog(null, o); 
     } 
    } 
} 

任何幫助將是有益的。

+0

songArray(宋); – athabaska

回答

0
songArray(); //<--- Im having issues right here// 

這不是一個靜態方法,它是Song類的實例方法,你需要Song實例調用該方法

new Song().songArray(Song); 

0

您需要使用的Song一個實例來調用類的方法。此外,您需要傳遞數組,因爲方法songArray()需要String array,但是您尚未在方法調用中提供任何參數。

new Song().songArray(Song); 
// new Song() creates a Song instance 
// songArray(song) calls the songArray method of Song class and passes the Song array to it. 
0

songArray(); //<--- Im having issues right here// 

不存在的方法。

而且該類歌還未創建,以便首先你需要

Song songClass = new Song(); 
songClass.songArray(Song); //<--- No issues right here// 
+0

songArray()不是靜態的... – TheLostMind

+0

是的,在創建類後更新了 –

+0

謝謝大家,我非常感謝這個論壇提供的內容,我很高興能夠幫助其他人,因爲我得到了幫助! – user3117058

1

你需要一個實例對象調用其他類的方法。

不喜歡你試圖維護Java命名約定此

new Song().songArray(Song); 

Song s = new Song() 
s.songArray(Song); 

更好的做法。

例如

更改字符串[]歌曲= {}; to String [] Song = {};並呼籲像下面

new Song().songArray(songs); 
0

嘗試這種::

import javax.swing.JOptionPane; 
public class SongTestDrive 
{ 
    public static void main(String[] args) 
    { 
     String[] songs ={"Song title: soul to squeeze","Artist: Red Hot Chili Peppers","Genre: Funk Rock","Year: 1993","Song title: Slaughtered","Artist: PanterA","Genre: Groove Metal","Year: 1994"}; 
     Song song = new Song(); // create object of song class, then use that object to call methods of Song class 
     song.songArray(songs); //<---there won't be any issue now// 
     // by doing songArray(), compiler thought that songArray() is part of SongTestDrive class hence the 'cannot find symbol songArray' exception 
    } 
} 
+0

非常感謝您,我感謝您抽出寶貴時間,不僅向我展示我的代碼被破壞的位置,而且還解釋了爲什麼會這樣! – user3117058

+0

不客氣。請接受你認爲解決了你的問題的答案,以便其他人能夠認識到問題已經解決。 –