coder101
coder101

Reputation: 850

Runtime Error for an anagram - Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

i am trying to solve this question https://www.hackerrank.com/challenges/anagram and here's my code

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;


public class Anagram {
public static void main(String[] args)
{
    Scanner reader = new Scanner(System.in);
    int t = reader.nextInt();


    while((t--)>0)
   {    
    String input = reader.nextLine();

    if((input.length())%2 == 1)
        System.out.println(-1);
    else
    {
        int x = input.length();
    int q = (int)(Math.floor((x/2)));

    String input1 = input.substring(0,q-1);

    int [] count1 = new int[26];
    for( int i = 0; i < input1.length(); i++ )
    {
        char ch1 = input1.charAt(i);
        count1[ch1-'a']++;
    }

    String input2 = input.substring(q,x-1);

    int [] count2 = new int[26];
    for( int i = 0; i < input2.length(); i++ )
    {
        char ch2 = input2.charAt(i);
        count2[ch2-'a']++;
    }

    int count =0;
    for(int j=0;j<26;j++)
    {
        count = count + Math.abs(count1[j]-count2[j]);
    }

    System.out.println(count/2);
    }
   }
  }
 }

i always get this error Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1911) at Anagram.main(Anagram.java:26)

i know that i am not picking the correct index for substring but it looked fine can anyone help me

Upvotes: 1

Views: 334

Answers (2)

Sandeep Mittal
Sandeep Mittal

Reputation: 57

Your substring indexes should be as follows: String input1 = input.substring(0,q); String input2 = input.substring(q,x); This is because the second parameter (the end index) is not inclusive. Also, based on my testing, the only time I get the StringIndexOutOfBoundsException is when I test with an empty string(""). But after the change I mentioned, you won't even get that error.

Upvotes: 2

fallen
fallen

Reputation: 31

your substring goes behind the limits for instance goes to -1, however it doesnt exist try to change that part

Upvotes: 0

Related Questions