Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Cannot Find The Error in The Code

cooldudeachyutcooldudeachyut Bijnor, IndiaMember Posts: 1

I was trying to create a program which can remove any repeating characters in a String. For ex-
Input: kamehamehaaaa
Output: kameh
This is the code:-

import java.util.Scanner;
class replace
{
public static void main (String args[])
{
Scanner br = new Scanner(System.in);
System.out.println("Enter a word");
String S=br.next();
int l=S.length();
String S1="",S2=S;
for(int i=0;i<l;i++)
{
S2="";
S1=S1+S.charAt(i);
for(int k=0;k<=i;k++)
S2=S2+S.charAt(k);
for(int j=i+1;j<l;j++)
{
if (S.charAt(i)!=S.charAt(j))
S2=S2+S.charAt(j);
else
l--;
}
S=S2;
}
System.out.println("Trimmed word : "+S1);
}
}

On running the program I get a StringOutOfBoundException error.
I am a noob and cannot figure out the mistake I did there. Please help me out!

Comments

  • SixtyHzSixtyHz USMember Posts: 13
    edited January 2015

    Looks like you have way too many loops, the first two seem to be copying the same thing to S1 and S2... Also some weird string manipulation is occurring with in those loops, it looks a bit more complicated than it should be... here's how i would approach this, written in untested pseudocode

    //At each char in your input string<br /> for every inputChar in inputStr<br /> {</p> <pre><code> bool weFoundChar = false; //check your output string to see if that letter is in it for every outputChar in outputStr { if outPutChar == inputChar { weFoundChar = true; break; // abort loop } } // if we haven't found the character then add it to output str if (weFoundChar == false) append inputChar to outputStr;

    }

Sign In or Register to comment.