Home:ALL Converter>Why am I getting a StringIndexOutOfBoundsException?

Why am I getting a StringIndexOutOfBoundsException?

Ask Time:2015-08-20T22:38:54         Author:shivakrishna9

Json Formatter

for(int i=0;i<5;i++) 
{           
  char ans = s.next().charAt(i);    
}

I am getting a StringIndexOutOfBoundsException. Why it is happening?

Author:shivakrishna9,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/32121212/why-am-i-getting-a-stringindexoutofboundsexception
dimo414 :

Because s.next() is returning a String with less than 5 characters. Try printing out s.next() to see the value if you expected it to be longer.",
2015-08-20T14:51:43
Meer Md. Mahbubuzzaman :

You are getting the exception cause you are trying to assign a char in your \"ans\" variable which is not available. The reason behind this is, the string you're getting by calling the 's.next()' method is not returning a string with at least 5 characters. Let's say the string is \"Me\" and you're trying to loop through it 5 times where there is only two characters. So when you're trying to look for the 3rd indexed character there is none and so you're getting the \"StringIndexOutOfBoundsException\"......",
2015-08-20T15:00:26
yy