Java非静态方法playCompletely不能从静态上下文中引用

问题描述:

我一直在试图创建一个方法(在一个单独的类中),它将String作为参数并使用预制的SoundEngine(不同的类)对象来播放该文件作为字符串输入。这是迄今为止的代码。问题出现在
SoundEngine.playCompletely(file);Java非静态方法playCompletely不能从静态上下文中引用

import java.util.ArrayList; 

public class AudioFileList 
{ 
    // Field for a quantity of notes. 
    private ArrayList<String> files; 

    // Constructor that initializes the array field. 
    public AudioFileList() 
    { 
     files = new ArrayList<String>(); 
    } 

    // Method to add file names to the collection. 
    public void addFile(String file) 
    { 
     files.add(file); 
    } 

    // Method to return number of files in the collection. 
    public int getNumberOfFiles() 
    { 
     return files.size(); 
    } 

    // Method to print the strings in the collection. 
    public void listFiles() 
    { 
     int index = 0; 
     while(index < files.size()) 
     { 
      System.out.println(index + ":" + files.get(index)); 
      index++; 
      } 
    } 

    // Method that removes an item from the collection. 
    public void removeFile(int fileNumber) 
    { 
     if(fileNumber < 0) 
      { 
       System.out.println ("This is not a valid file number"); 
      } 
     else if(fileNumber < getNumberOfFiles()) 
      { 
       files.remove(fileNumber); 
      } 
     else 
      { 
       System.out.println ("This is not a valid file number"); 
      } 
    }  

    // Method that causes the files in the collection to be played. 

    public void playFile(String file) 
    { 
    SoundEngine.playCompletely(file); 
    } 

} 

任何帮助非常感谢。

+1

当你输入你的问题,右边是标记一箱**如何格式化**。值得一读。我已经采取了初步措施为您设置代码格式,因为我无法立即回想您是否可以通过rep = 1编辑您的问题... – 2010-11-21 14:17:35

+0

问题的格式不能帮助我们正确地解答您的问题,请先修复它。为此使用'101010'。 //在调用它的非静态方法之前,你应该创建一个'SoundEngine'的实例,或者使该方法静态。 – khachik 2010-11-21 14:18:43

+0

@khachik对不起,您是什么意思由'101010'? – thelost 2010-11-21 14:21:00

SoundEngineplayCompletely函数是一个实例函数,而不是一个类函数。因此,而不是:

SoundEngine.playCompletely(file); // Compilation error 

你想:

// First, create an instance of SoundEngine 
SoundEngine se = new SoundEngine(); 

// Then use that instance's `playCompletely` function 
se.playCompletely(file);