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 "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.
Related
I am new to java. My code is:
public class Hi {
public static void main(String[] args) {
System.out.print("Hi, ");
System.out.print(args[2]);
System.out.print(",");
System.out.print(args[1]);
System.out.print(", and");
System.out.print(args[0]);
System.out.println(".");
}
}
I get the following exception upon running this program:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Hi.main(Hi.java:5)
I would be glad to know why I had got this exception and how to resolve it.
You are passing parameters which is less than 3, thats why you are getting this error.
try like below command,
java hi test test test
Either you dint passed command line arguments while executing the program or args.length < 3
You would have got this exception if you had tried to run this program providing 2 or fewer arguments.
args[0] will be the first index of the array.
args[1] will be the second index.
args[2] will be the third index of the array.
This is because array index starts with 0 and ends with n-1 for arrays in Java. (n is the size of the array).
Command line way
This program will run fine, if you run the program as
java Hi Demo Test Argument
Here Demo is at args[0], Test is at args[1] and Argument is at args[2].
Using Eclipse IDE
Right click on the class file.
Select Run As and select Run Configurations
Double Click on Java Application
Go to the Arguments tab and provide three arguments in the Program
Arguments textarea separated by spaces as shown in the image below.
Now click on Apply and then on Run
I am learning java using a book. There is this exercise that I can't get to work properly. It adds two doubles using the java class Double. When I try to run this code in Eclipse it gives me the error in the title.
public static void main(String[] args) {
Double d1 = Double.valueOf(args[0]);
Double d2 = Double.valueOf(args[1]);
double result = d1.doubleValue() + d2.doubleValue();
System.out.println(args[0] + "+" + args[1] + "=" + result);
}
Problem
This ArrayIndexOutOfBoundsException: 0 means that the index 0 is not a valid index for your array args[], which in turn means that your array is empty.
In this particular case of a main() method, it means that no argument was passed on to your program on the command line.
Possible solutions
If you're running your program from the command line, don't forget to pass 2 arguments in the command (2, because you're accessing args[0] and args[1])
If you're running your program in Eclipse, you should set the command line arguments in the run configuration. Go to Run > Run configurations... and then choose the Arguments tab for your run configuration and add some arguments in the program arguments area.
Note that you should handle the case where not enough arguments are given, with something like this at the beginning of your main method:
if (args.length < 2) {
System.err.println("Not enough arguments received.");
return;
}
This would fail gracefully instead of making your program crash.
This code expects to get two arguments when it's run (the args array).
The fact that accessing args[0] causes a java.lang.ArrayIndexOutOfBoundsException means you aren't passing any.
The static method main, which receives an array of strings. The array should have two elements: the path where the files are located (at index 0), and the name of the files to process (at index 1). For example, if the name was “Walmart” then the program should use “Walmart.cmd” (from which it will read commands) and “Walmart.pro” (from which it will read/write products).
I don't want anyone to write the code for me because this is something I need to learn. However I've been reading this through and the wording is confusing. If someone could help me understand what it wants from me through pseudo-code or an algorithm it would be greatly appreciated.
Where I'm confused is how to initialize arg[0] and arg[1] and exactly
what they are being initialized to.
The main method's String array input argument consists of whatever String arguments you pass to the program's main method when you run the program. For example, here is a simple program that loops over args and prints a nice message with each argument's index and value on a separate line:
package com.example;
public class MainExample {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.printf("args[%d]=%s\n", i, args[i]);
}
}
}
Once you've compiled the program, you can run it on the command-line and pass it some arguments:
java -cp . com.example.MainExample eh? be sea 1 2 3 "multiple words"
Output:
args[0]=eh?
args[1]=be
args[2]=sea
args[3]=1
args[4]=2
args[5]=3
args[6]=multiple words
So lets explain to you
Create a class Inventory : if you don't know how to create a class google it just as is
The static method main: Every executable class in java (at least from the console) has the main method you should google java main method and propably in the same place you find it you will see the default arguments that it receives
When you learn about the default arguments of method main you will undertand about the 'args' that has to be on it
You will have t study the class String google it "java String class"
You will have to study the class File google it "java File class"
At the end everything else would be just logic and I beleave you have learned some at this point.
public class Inventory { // class inventory
public static void main(String[] args) // main method
{
if(args.length==2){ // check if args contains two elements
String filePath = args[0];
String fileName = args[1];
filePath+= System.getProperty("file.separator")+fileName;
File fileCMD = new File(filePath+".cmd");
//fileCMD.createNewFile();
File filePRO =new File(filePath+".pro");
//filePRO.createNewFile();
}
else {
//write the code to print the message Usage: java Inventory Incorrect number of parameters for a while and exit the program.
}
}
This is what I've understood. Basically you have to write a program to create two files, one called fileName.cmd and the other fileName.pro. You have to construct the path of the files using the arguments (input parameters of the main method) and system's file separator. If the arguments don't have two elements you have to print the 'invalid' message. That's it.
Where I'm confused is how to initialize arg[0] and arg[1] and exactly
what they are being initialized to.
You have to use command line to pass the arguments and launch the program , something like the following code in cmd or terminal:
java inventory thePath theFileName
That's how it get initialized.
I am trying to test an ANTLR grammar with such a standard test rig
import org.antlr.runtime.*;
class Main {
public static void main(String[] args) throws Exception {
SampleLexer lexer = new SampleLexer(new ANTLRStringStream(args[0]));
SampleParser parser = new SampleParser(new CommonTokenStream(lexer));
parser.program();
}
}
I have a test file called mytest00. Now I want to use this file as input. I suppose I am doing a stardard IO redirection here.
bash-3.2$ java Main < mytest00
But it gives me such an error message. What is the problem please? Thanks.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main(SampleTest.java:5)
You're trying to use args[0] but you haven't actually passed in any command line arguments - you've just redirected a file into the standard input of the process. So the array has no elements, and you're getting an exception because you're trying to get the first element of that empty array.
It's not really clear that you actually want ANTLRStringStream. I suspect you want ANTLRInputStream wrapping System.in if args.length == 0, and ANTLRFileStream(args[0]) otherwise.
when you use < as parameter , OS treats it as input redirection . so it will check for it and it won't pass argument the java main()
What the exception means and how to deal with exceptions generally
at Main.main(SampleTest.java:5)
The problem appears in 5 line of your code, which is:
SampleLexer lexer = new SampleLexer(new ANTLRStringStream(args[0]));
and the Exception is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
which means you're trying to retrieve 0-element from your array args, the array has been accessed with an illegal index because the array is empty (size=0)
Example solution
You want to use this constructor:
public ANTLRStringStream(String str)
To do this you can:
read standard input to some String
pass this String to ANTLRStringStream constructor
I usually run this program via a command line like so:
java Program <TestClass.java
Which as I understand, forces the contents of TestClass.java to the console as user input.
i.e. It would be like executing
java Program
and then typing what ever is in TestClass.java
My problem is getting this happening in Eclipse. I can't figure out how to do it.
I would have thought that adding
<TestClass.java
to the program arguments in the run configuration would work, but it seems not.
Any suggestions?
How about adding this on top of your main.
InputStream in;
if (args.length > 0) {
in = new FileInputStream(args[0]);
} else {
// fallback
in = System.in;
}
And then you add the filename as an argument, as if you're running java Program TestClass.java. This way, it will work whether you run it as before or using the filename as an argument.