I am a new Java programmer. The following is my code:
public static void main(String[] args) throws Exception {
BPM2SampleProcessor processor = new BPM2SampleProcessor();
processor.setSampleSize(1024);
EnergyOutputAudioDevice output = new EnergyOutputAudioDevice(processor);
output.setAverageLength(1024);
Player player = new Player(new FileInputStream(args[0]), output);
player.play();
log.log(Level.INFO, "calculated BPM: " + processor.getBPM());
}
It shows a runtime error as
Exception in thread 开发者_StackOverflow中文版"main" java.lang.ArrayIndexOutOfBoundsException: 0 in the following line:
Player player = new Player(new FileInputStream(args[0]), output);
Please explain what the error is and how to overcome it.
Are you running your code from the command line or from an IDE like eclipse?
Every main method has a String[] (usually called args) which you can see in the first line of your code.
The program is trying to use args[0] as the name of the file to open. (which you supply from the command line, or configure in the IDE). But right now the args variable doesn't have anything in it. Try replacing args[0] in your program with a string representing the file you want to open. You will have to make sure that you get the correct path.
You're likely not passing any command line parameters into your program when you run it, so the size of args is 0, and args[0] will throw the exception your seeing. The solution is to pass a parameter, presumably an appropriate file name in when you run this program by calling
java MyProgram myfilename.ext
When you run the program you have to give an argument. the args[0] is coming from the user input which you havent given. something like java MyProgram 5
You are not passing the argument required args[0]
and hence it is throwing the error.
精彩评论