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

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!

Related

Index 0 out of bounds for length 0 [duplicate]

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.

Error after compiling Java project : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

I am working on a project for school. The project is a game where the user needs to guess the price of an object. The price is generated randomly. The user has 5 chances to guess it. if he doesnt, th game is over and is asked if he wants to replay or not. The name of this game could be known as The Price is Right. My problem is that when i run the project it crashes just before taking the answer of the user, to know if he wants to replay.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at pkgthepriceisrightv1.ThePriceisRightV1.main(ThePriceisRightV1.java:102)
Java Result: 1
BUILD SUCCESSFUL (total time: 7 seconds)
This is the error. I dont know what is the problem....
And here is the code lines where i am taking the information, the yes or no from the user, wich is the line 102, in the error code, i have declared all my variables. valeur_recommencer is a char, and recommencer is a string.
All my code is in Java. Excuse me for the language of the code, its all in french, a requirement for school.
recommencer = lire.nextLine();
valeur_recommencer = recommencer.charAt(0);
This returns empty string "".
recommencer = lire.nextLine();
so when you try to find the first char of empty string, it ends with exception.
Ok found my mistake. I needed to add an other Scanner. If this error code is shown for any body else, try adding an other scanner. The sacnner could not read too much of answers from the user, so is crashes. I think it could solve the problem

Index Out of Bounds Error

I'm running a simple java program. I programmed it in Netbeans. Everything worked great. Attempted to transition code to use Ant because that's what my class requires, and I'm getting a weird error.
All text coming in from the .txt is in the format,
Baker William Chavez 04/01/05
Sanchez Jose Chavez 06/15/05
etc ...
There about 20 entries, 3 names and a date. Each entry is on its own line.
I'm using this code to read it in.
while ((line = br.readLine()) != null) {
//formatting data correctly
String [] info = line.split(" ");
for(int i = 0; i < info.length; i++){
System.out.println(info[i]);
}
System.out.println(info[0]);
System.out.println(info[1]); /* this line of code */
}
So every info [] is of length 4. When I run the for loop, it prints out everything exactly as expected. Printing out "info[0]" works exactly has expected.
But for some reason when I attempt to print out "info[1]", I get an
java.lang.ArrayIndexOutOfBoundsException: 1
error. I have no explanation for why this happens. When I don't attempt to print out info[1] by itself, my program works correctly. In the for loop, info[1] gets printed out, because the for loop loops through 4 times. This code worked perfectly in Netbeans, but using Ant is doesn't work.
Does anyone know adding or removing just one line,
System.out.println(info[1]);
causes my program to run or throw an exception?
I'm running Ant 1.9.2
I'm running Java 1.7.0_17
I've checked this multiple times, so I'm pretty sure its not something I've made an erro ron. I'm a fairly experienced programmer, so I pretty confident it's not my error. It runs well in Netbeans. I don't have an explanation for the error.
edit 1.
My code throws an error the second time threw the while loop.
Printing out the info[] length, or the line itself works great with I don't print out line[1] by itself. It stills fails and throws an error when I printout the info[1] by itself.
http://pastebin.com/NAUeDsZH
Edit 2.
#Millie Smith was on the right trail because my .txt file wasn't correctly formatted. Viewing it in notepad for some reason didn't display the extra space in between each line.
http://pastebin.com/njjdSHHZ
My correct pastebin.
I was attempting to use code to strip out all of the blank space, commas, new lines, and such,
line = line.replaceAll("\\s+", " ");
line = line.replaceAll(",","");
line = line.replaceAll("\\n", "");
line = line.replaceAll("\\r", "");
String [] info = line.split(" ");
I incorrectly assumed that that code would take care of any irregularities. I was wrong. So on my first pastebin, I formatted the code to what I thought I was dealing with, which was also incorrect.
So if I test for line.length() > 1, that gives me my results that I am looking for. I'm not an experienced programmer as I think I am.
Your last line of the file is BLANK ( probably just a end of line marker ) and this is causing the last .split(" ") to assign a single element array with nothing in it but an empty string in the first position.
Make sure your file doesn't have a ZERO length line as the last line or any of the lines.
Learn to use the step debugger, it is your best friend, and step through the code and see what line is equal to on the very last iteration.
Ant and Netbeans have nothing to do with this error, it is completely data related and we can't see your entire data file in its native format

How to Run a Simple Java Program in Eclipse?

As you can probably understand from the question itself, I'm new to Java.
I was given an exercise to write a Java program which receives a character, prints it and the next character in the Unicode table.
Now, I have the solution to this exercise:
public static void main(String[] args){
char c = args[0].charAt(0);
char c1 = (char)(c + 1);
System.out.println(c + "\t" + c1);
}
I understand basic idea of this code, but I'm trying to run this code in Eclipse I get an annoying error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at MainClass.main(MainClass.java:9)
Note: I have yet to run a Java program that actually receives something as a parameter so I guess it's a stupid beginners' mistake... Here is the full code that I tried to compile in Eclipse:
public class MainClass {
/**
* #param args
*/
public static void main(String[] args){
char c = args[0].charAt(0);
char c1 = (char)(c + 1);
System.out.println(c + "\t" + c1);
}
}
Thanks in advance
Select "Run -> Run Configurations" from the menu.
Search for you project in the list on the left and select it.
Select the "Arguments" tab on the right.
Write the argument you want to pass to the programm in "Programm arguments".
Click "Run"
Right click on your java file in project explorer of your eclipse. Then Run As> Run Configuration
Then you will get a window. Like-
Click on Arguments Tabs, and then write some text there, may be a character.
And then Click on Apply button and Run Button.
The default run configuration in Eclipse runs a Java program without any arguments, hence the ArrayIndexOutOfBoundsException. Your code is trying to get first element of the args array when there aren't any!
You can edit the run configuration to provide the arguments to run your program with. Then it should not throw this exception.
However, a good practice is to check the size of array before accessing it's elements, more so when the array is coming as an argument from outside of your code.
This is a great question with some very good answers. I would like to add some pointers about how to debug your own program. Debugging is as important (if not more important) than writing code.
For one thing, Eclipse has some great debugging features. You can use this debugger to find problems in your code. I suggest that you learn how to use it. In particular, you can set watches for variables to see what value they have as you step through the execution of your code.
Alternatively, you can add calls to System.out.println() to print out the values of any variables. For example, adding the following line at the beginning of your code might help you narrow down the problem:
System.out.println(args[0]);
This would also give an ArrayIndexOutOfBoundsException if no command-line arguments are given. Then you could do something like
System.out.println(args.length);
which would print out 0. This then gives you a clue as to where the problem is.
Of course, even when you get to this point, you still might not know how to solve the problem. This is where sites like StackOverflow come in handy.
Good luck with your Java experience. Please come back when you need more help.
If your Run Configurations are in place (as already shown in above answers):
Shortcut to Run a class is:
Ctrl + F11

running external program in java

If I am running external program(batch file) from java then, What I need to do:
if (process.exitValue() == 0) {//means executed successfully ???
Can't the return value be something else and batch executed successfully.
Is that the only way to check??
I'm a bit confused by your wording, but by convention, [exitValue()](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html#exitValue()) returns 0 upon a successful execution. This is, as far as I know, the only way to check.
EDIT:
I suppose you could use [getErrorStream()](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html#getErrorStream()) - I assume it'll be blank if there are no errors in the process...
Pick one from here
You could read the output stream ( or the error stream ) and interpret it
The exit code of the batch process will be defined by that process but generally an exit code of 0 is defined as successful and a non zero value indicates that something went wrong. In your batch file you can set the return code by calling:
EXIT /B %ERROR_CODE%
%ERROR_CODE% is the number that will be returned as the exit code.
On Linux, your program can return any status you want. By convention 0 means success.
For example, if you execute a shell script, the return status will be the return status of the last command executed in your script.
In many programs 0 is is success, negative numbers are errors and positive numbers are warnings. Of course this is just a convention and it all depends on what convention was followed. In most programming languages you can define an exit code for a program and that is what is picked up.
In Java System.exit(n)
In C main is defined as int main(int argc, char* argv[]) and the return from main is the return from the program.

Categories