Вопрос

i am writing a program to delete the repeated letters in a word and it is showing out of bounds error in line 22 i cant figiure out what's the problem. heres the code

import java.io.*;
public class p23
{
    public static void main(String args[])throws IOException
    {
        String inp , z = "" ;
        int len , i ,j , l;
        char x ,y ;
        InputStreamReader read=new InputStreamReader(System.in);
        BufferedReader in=new BufferedReader(read);
        System.out.println("Enter a string");
        inp = in.readLine();
        inp = inp + ' ';
        len = (inp.length())-1;
        for (i=0;i<=len;i++)
        {
            x = inp.charAt(i);
            z = z + x ;
            l = i + 1 ;
            for ( j=i ; j<len ; j++)
            {
                y = inp.charAt(j);
                if(x==y)
                continue;
                else
                z = z + y;
            }
            inp = z ;
            z = " " ;
            if (inp.charAt(l)==' ')
            break ;
        }
        System.out.println("new String "+inp);
    }
}

please suggest an option

Это было полезно?

Решение

Before your for() loop ends, i will have a value of len. Then you set l = i + 1 which is out of bounds and fetch later on inp.charAt(l). That's it.

After further investigation (I have not ran the program in my IDE, just read your code) I observed the true cause I guess. Look at inp = z for each iteration of i. When i growth, z becomes shorter and shorter, because it starts with " ", concats one x and the rest of len - i. This will be shorter than your l, which will be someone in time len + 1 or at least len. The value of l is not synchronized with the variation of inp in each iteration of the i loop.

Другие советы

See the comments in the code below, it shows one of the cases of failure.

{
    String inp="aaa" , z = "" ;
    int len , i ,j , l;
    char x ,y ;
    inp = inp + ' ';
    len = (inp.length())-1;
    for (i=0;i<=len;i++) // i is 0
    {
        x = inp.charAt(i); // X is 'a'
        z = z + x ; 'z is 'a'
        l = i + 1 ; // l is 1
        for ( j=i ; j<len ; j++)
        {
            y = inp.charAt(j);
            if(x==y)
            continue;
            else
            z = z + y;
        }
        // z is still 'a'
        inp = z ;
        // inp is also 'a'
        z = " " ;
        // inp.charAt(1) -> OOB
        if (inp.charAt(l)==' ')
        break ;
    }
    System.out.println("new String "+inp);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top