Index 0 out of bounds for length 0 [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
Here i am getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
System.out.println(input);
while(true){
if(args[0].equals("k")){
System.out.println("k");
}
}
}

You need run the code on cmd as java MyProgram abc xyz then args will contain ["abc", "xyz"].Maybe you are not doing that right now and therefore getting the error.

You need to provide Command Line Arguments like so:
java MyClass k foo bar
These arguments are passed to the array args[] which will then contain {"k", "foo", "bar"}
Therefore args.length will be 3 and args[0] will be k

If you are executing through IDE and not setting arguments OR not passing command line arguments while running through cmd, you'll get this error.
But for this program, even if you pass arguments, it will run in infinite loop probably as while condition is always true.

You are executing this java class without arguments. In that case, args[0] does now exist, and thus the Exception with Error message.
You can modify the if in this form:
if(args[0].equals("k") && args.length > 0 )
so you do not get exception with message
Index 0 out of bounds for length 0
Your program is producing output without error, when Running the program with argument "k" produces the infinite look of printing k. For this you need to run command the java printKjavaFile k , or start it from IDE with this argument.

You are doing 2 things at the same time:
ask for user input via stdin, when the program is running already
parsing the args[], which should be given when the program starts to run
and expect they work together. But they are different.
I suppose you run the app like: java MyClass without adding extra args after this. You can:
provide arg k after java MyClass, so args[] becomes a non-empty array
stop trying to use args, but just focus on input, which is the line you read from user input.

Related

Java: Making an Optional Command Line Argument

I am working on a program that is supposed to take one required command line argument and one optional command line argument. The first argument is the name of an output file where data will be written to, and the second is a number that will be used to calculate the data to be written to the output file. If the user does not enter a number, then it should just use a default value to calculate the data. For example, if the user entered command line arguments "Foo.csv 1024" the program would use 1024 to calculate the data and write it to Foo.csv, but if the user only used the command line argument "Foo.csv" then the program would use a default value of 2048 to calculate the data and write it to Foo.csv. I am creating/running this program using the Intellij IDE. How would I do this? Any advice/suggestions would be much appreciated.
Your program seems to be simple, so the solution is also simple for this particular case. You can test how many arguments were passed to the program checking the argument args of your main function:
public static void main(String[] args){...}
args is an array that contains the arguments passed to your program. So if your program is called prog and you run it with prog Foo.csv 1024, then args will have:
args[0] = "Foo.csv";
args[1] = "1024";
With this, you know which arguments were passed to your program and by doing args.length, you can know how many they were. For the example above, args.length=2 If the user didn't indicate the last argument ("1024"), then you would have args.length=1 with the following in args:
args[0] = "Foo.csv";
So your program would be something like:
public static void main(String[] args){
//The default value you want
int number = 2048
if(args.length==2){
number = Integer.parseInt(args[1]);
}
//'number' will have the number the user specified or the default value (2048) if the user didn't specify a number
}
To supply arguments to your program you must run it on a console or some kind of terminal. Using IntelliJ (or any other IDE) it's also possible to run the program with arguments, but you specify those in the Run Settings.
If you want a more complex treatment of arguments, usually what you want is done by argument parsers. These are usually libraries that take you argv and help you reading arguments to your program. Among other things, these libraries usually support optional arguments, arguments supplied via flags, type checking of arguments, creating automatic help pages for your commands etc. Consider using an argument parser if your argument requirements are more complex or if you just want to give a professional touch to your program :)
For java i found this particular library: http://www.martiansoftware.com/jsap/doc/

Sequence of Sysout result

While practising Java arrays in Eclipse, I have encountered this weird behaviour of arrays.
public class base3 {
public static void main(String[] args) {
int arr[]= new int[25];
System.out.println(arr[0]);
//System.out.println(arr[25]);
System.out.println(arr[-10]);
}
}
Output of this is:
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -10
at base3.main(base3.java:6)
But as soon as I change the index of third sysout from -10 to -11, the sequence of output changes.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -11
at base3.main(base3.java:6)
0
So why does the output sequence changes along with array index.
This is happening due to the the output is written to different file. The output 0 is printed to standard output(fd 1) and the exception to standard error(fd 2). You could see this when you redirect standard error to /dev/null
❯ java base3 2>/dev/null
0
See how you don't get exception here. So the order here will not be predictable due to output written to different files.
The java documentation says Prints this throwable and its backtrace to the standard error stream..
I think you are looking at a race condition between standard error and standard out to print things to the console. When the exception ArrayIndexOutOfBoundsException gets thrown, it is not handled by printing to System.out but to System.err. Since both streams have to share the console resource the order in which they get access determines the order of the print statements.
The change of -10 to -11 should not influence the result. It is the time between the call to System.out.println(arr[0]); and System.out.println(arr[-10]); that influences the order of the output.

main method String[] args issue

I'm reading Sams Teach Yourself Java in 24 Hours and came across this code:
class NewRoot {
public static void main(String[] args) {
int number = 100;
if (args.length > 0) {
number = Integer.parseInt(args[0]);
}
System.out.println(“The square root of “
+ number
+ " is "
+ Math.sqrt(number));
}
}
But in order for the code to be compiled, the writer enters 169 in the Arguments field in the
Run>Set Project Configuration>Customize
menu (in NetBeans IDE).
So my question is: what's the purpose of the specific field? Does 169 means something or is it just a random number? It's a pity the writer doesn't say anything about it!
The author is giving you an example of running a program with arguments given via the terminal. This is usually done in your terminal or command prompt by running the code as such
javac ProgramName.java
java ProgramName <arguments>
Since you are writing and running your program in Netbeans, and wont be using the terminal, you can configure to run the project with a given command line argument. This is what you are doing in the netbeans menus.
The String "169" only has meaning for the given program. The author is trying to demonstrate how the program will run given a command line argument, in this case he sets it to an arbitrary value "169."
In your code you are taking this String and turning it into an int.
The number 169 is almost certainly meaningless and arbitrary; it is used by the author merely as an example. Now let's break the code down line by line to address your concerns.
args contains any command line arguments as an array of strings:
public static void main(String[] args) {
The author declares a variable of type int and calls it number. He assigns an initial value of 100. This would appear to be a randomly selected number to demonstrate the concept - a common approach in programming books.
int number = 100;
He then checks if there were any command line arguments supplied; if there were, args.length will be greater than zero:
if (args.length > 0)
If there is a command line argument he parses the first argument into the number variable (this operation could fail by the way if you supply a non-numeric first argument):
{
number = Integer.parseInt(args[0]);
}
Note that if there is no command line argument, number is not overwritten. So, call the program without a command line argument and it will display the square root of 100. Call it with an argument of 169 (surely another number picked out of the air) and it will show you the square root of 169.
Command line arguments will be packed into args; input from keypresses etc after the program has started will not.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 What's Going Wrong?

I am trying to code this program to read 6 values from the command line as coordinates and use these coordinates to calculate the area and perimeter of the triangle formed.
However, I'm getting this error message when running the program:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at geometry.ThreePoints.main(ThreePoints.java:26)
What's going wrong?
My Code with the error message:
you are running your program without any argument in eclipse.
go to run > run configuration and add arguments:
This programm doens't read from command line, it reads the start arguments. which i guess are not there.
edit:
an example for reading from the command line, you'll find at the oracle docs
Looks like you are not passing parameters while trying to run the program.
Go to run configuration in eclipse and add your parameters there. this will fix your problem.
In eclipse Go To RunAs-->Run Configurations.. --> Arguments --> Program Arguments.
Put there arguments whitespace separated.
Use args.length to check the length of arguments.
Use args.length to determine the number of arguments before you read them.
if (args.length < 6) {
System.out.println("Number of argument too small. Must be 6, but was "+ args.length +".");
}
You've probably made a mistake entering the arguments. You should always check the number of array elements before you access them!

difference between System.exit(0) and System.exit(-1) [duplicate]

This question already has answers here:
Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java
(12 answers)
Closed 7 years ago.
Can any one share to me difference between System.exit(0) and System.exit(-1) it is helpful if you explain with example.
It's just the difference in terms of the exit code of the process. So if anything was going to take action based on the exit code (where 0 is typically success, and non-zero usually indicates an error) you can control what they see.
As an example, take this tiny Java program, which uses the number of command line arguments as the exit code:
public class Test {
public static void main(String[] args) throws Exception {
System.exit(args.length);
}
}
Now running it from a bash shell, where && means "execute the second command if the first one is successful" we can have:
~ $ java Test && echo Success!
Success!
~ $ java Test boom && echo Success!
System.exit(0) means it is a normal exit from a program.But System.exit(-1) means the exit may be due to some error. Any number other that zero means abnormal exit.
The parameter of System.exit(int) is the return value of your program, which can be evaluated in batch jobs (usually for console programs). By convention, every value other than 0 inidaces that something went wrong.
If you run your Java program in Linux/Unix you can examine the result using echo $? command. This is why it is important to call System.exit(0) (this is done for you if you don't) if everything is fine and System.exit(non-zero) otherwise.

Categories