The following program is the GAME OF THRONES-1 problem from hackerrank. But I am facing the given error while executing. I would be grateful if anyone could help. The error would be:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:646)
This is my code
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.Arrays;
public class try123
{
public static void main(String[] args)
{
Scanner myScan = new Scanner(System.in);
String inputString = myScan.nextLine();
String s=inputString; //abccba
String ans; //YES or NO
String A="";
int flag=0;
String news="";
String nrev="";
String rev="";
//char arr[]=new char[100000];
char arr[]=inputString.toCharArray();
Arrays.sort(arr);
String b= new String(arr); //sorted string
int len=b.length();
if((len%2)!=0)
{
A=b.substring(len-1,len);
len=len-1;
b=b.substring(len-1);
flag=1;
}
for(int l=(len-1);l>=0;l--)
{
rev=rev+b.charAt(l);
}
for(int i=1;i<len;i=i+2) //len=6
{
news=news+b.charAt(i)+rev.charAt(i-1);
}
if(flag==1)
news=news.substring(0,(len/2)-1)+A+news.substring((len/2),len-1);
for(int o=(news.length()-1);o>=0;o--)
{
nrev=nrev+b.charAt(o);
}
if(news==nrev)
ans="YES";
else
ans="NO";
System.out.println(ans);
myScan.close();
}
}
The problem seems to be here:
for(int i=1;i<len;i=i+2) //len=6
{
news=news+b.charAt(i)+rev.charAt(i-1);
}
You are increasing i by 2, so for even len
values, you would exceed the character limit for your string (which is why you're seeing this exception come)
java.lang.StringIndexOutOfBoundsException: String index out of range
These lines leads you to the error :
if ((len % 2) != 0) {
A = b.substring(len - 1, len);
len = len - 1;
b = ;
flag = 1;
}
for (int l = (len - 1); l >= 0; l--) {
rev = rev + b.charAt(l);
}
Before these lines, len
is the length of b
, on the third line, it becomes b's length - 1, and then you put in b
b.substring(len - 1)
, this means : the last 2 char of b. Now b is 2 character long, but len is still the original length - 1. Then you set int l = (len - 1)
, and do b.charAt(l)
. B is 2 character long and you try to access the l-th character, out of range.
The problem is here :
if((len%2)!=0)
{
A=b.substring(len-1,len);
len=len-1;
b=b.substring(len-1); // this returns a String with the last 2 characters of
// the original
flag=1;
}
When the input String has an odd length, you are keeping just the last two characters of that String.
I think you meant to remove only the last character of the String, which should be done like this :
if((len%2)!=0)
{
A=b.substring(len-1,len);
len=len-1;
b=b.substring(0,len); // this would return the original String minus the last
// character
flag=1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.