Here is my code, i am getting the following error message. How do i handle it?

package simp;
import java.io.*;


public class fCase {

public static void main(String [] args) throws IOException {


BufferedReader readObject = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your expressions here");
String userEntry = readObject.readLine();

String [] toki = userEntry.split(" ");

for (int i=0; i<=toki.length; i++) {
    
System.out.println(toki [i]);
//System.out.println(i + ": " + args[i]);

}

 }
   }

After inputing the following expression, this follows;

Enter your expressions here
what is your name?
what
is
your
name?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at simp.fCase.main(fCase.java:24)

Edited 6 Years Ago by peter_budo: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks)

It comes down to basics. Array of length 10 is array starting with object at position 0 and with last on position 9.
So considering you just run "i++" on 8 which will become 9. The termination expression "i<=toki.length" will check if "i" is smaller OR equal to array length. In this scenario it is still TRUE, therefore another increment and we land with "i=10".

Now you tell me what will be outcome of termination exception...

peter_budo:

thank you for the quick reaction. I an new to java hence am trying to get the basics as well.

i would appreciate if you could indicate to me out to address this proble in the code and some suggestion on the concept will also be beneficial.

Bottom line is array indexing is zero based. The maximum index you can use is one less than the size of the array. Your code tries to use an index equal to the size of the array.

Look at the condition in the for() loop

Edited 6 Years Ago by NormR1: n/a

This question has already been answered. Start a new discussion instead.