0

I wrote this program in java and I m getting this error.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
        at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
        at java.base/java.lang.String.charAt(String.java:702)

There is problem in charAt(i), but I'm unable to find what's wrong here. The syntax is correct then why is there an exception? Can anyone help me with this?

HashSet<String> set = new HashSet<String>();
TreeMap<String,String> mp = new TreeMap<String,String>();
Iterator<String> itr = set.iterator();

        while (itr.hasNext())
        {
            String str = itr.next();
            int len = str.length();

            char[] word = new char[len];
            
            for (int i = 0;i < n;i++)
            {
                int index = (i + key) % len;
                word[index] = str.charAt(i);
            }
            
            String x = toString(word);
            
            if (set.contains(x) == true)
                mp.put(str,x);
        }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Raghav Lakhotia
  • 41
  • 1
  • 1
  • 6

2 Answers2

0

instead if <n use <len in your loop

JavaMan
  • 1,142
  • 12
  • 22
0

you have not defined n anywhere in the code and used it in for loop so it is taking the default value of n and giving you the error, you can try this and check if the problem still exists:

HashSet<String> set = new HashSet<String>();
TreeMap<String,String> mp = new TreeMap<String,String>();
Iterator<String> itr = set.iterator();

        while (itr.hasNext())
        {
            String str = itr.next();
            int len = str.length();

            char[] word = new char[len];
            
            for (int i = 0;i < len;i++)
            {
                int index = (i + key) % len;
                word[index] = str.charAt(i);
            }
            
            String x = toString(word);
            
            if (set.contains(x) == true)
                mp.put(str,x);
        }
Binni G.
  • 21
  • 1
  • 6