i've got the following program: i have a jar file which is getting 4 parameteres from main method :input file,order by, sort direction, output file. The input file is the file where information will be read , order by is sorting by (test,runs , etc), sort direction (asc, desc) and outputfile where information will be saved. Here is my code in main method :
if (args.length > 0)
{
if (args[0].isEmpty())
{
System.out.println("Enter input file");
System.exit(1);
}
else
{
args[0] = inputFile;
}
if (args[1].isEmpty())
{
System.out.println("Enter order by");
System.exit(1);
}
else
{
args[1] = orderBy;
}
if (args[2].isEmpty())
{
System.out.println("Enter sort direction");
System.exit(1);
}
else
{
args[2] = sortDirection;
}
if (args[3].isEmpty())
{
System.out.println("Enter output file");
System.exit(1);
}
else
{
args[3] = outputFile;
}
}
else
{
System.out.println("Must enter parameteres!");
System.exit(0);
}
SaveInfoManager.SaveInFile(inputFile, sortDirection, orderBy, outputFile);
And i have a following error: ArraysIndexOutOfBoundsException when i do not enter some argument. Example i do not enter the 3rd argument which is sort direction and i want to print message that is not entered. But i do not understand why is throwing that exception even i make a check. Can you tell me where is my fault and how i can do it properly ?
argsarray has the size of the number of provided arguments. You'd better check the size of the array to know how many were provided.args.length > 0before accessing any args. That tells youargs[0]is within bounds, but that's all. You can't safely accessargs[1]without checkingargs.length > 1, orargs[2]without checkingargs.length > 2, etc.