3

I want the following output for the following input:

input: adele
output: ae

Code:

public class delDel {
    public static String delDel(String str) {
        StringBuilder sb = new StringBuilder();
        if(str.length() < 3){
           return str;
        }
        else if(str.substring(1, 3).equals("del")){
            StringBuilder afterRemove = sb.delete(1, 3);
            return afterRemove.toString();
        }
        else{
           return str;
        }

   }

   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

      String yourStr = input.nextLine();

      System.out.println(delDel(yourStr));
   }
}

But I keep getting the same input.

1
  • 1
    Try some System.out.println to debug specially inside the else if.... do you arrive... what is inside of sb there is something? You will save a lot of time if you learn some simple debugging techniques Commented Nov 28, 2015 at 18:03

1 Answer 1

6

There are multiple problems here:

  • Your StringBuilder isn't initialized with the input String. It should be StringBuilder sb = new StringBuilder(str); As such, it is always empty.
  • substring and delete methods work with the last index exclusive, not inclusive. So to take a substring of length 3 starting at index 1, you need to call str.substring(1, 4).

Corrected code:

public static String delDel(String str) {
    StringBuilder sb = new StringBuilder(str);
    if(str.length() < 3){
       return str;
    }
    else if(str.substring(1, 4).equals("del")){
        StringBuilder afterRemove = sb.delete(1, 4);
        return afterRemove.toString();
    }
    else{
       return str;
    }
}

Side-note: since you are only using the StringBuilder in one case, you could move its declaration inside the else if (this way, you won't create a useless object when the String is less than 3 characters).

Sign up to request clarification or add additional context in comments.

3 Comments

If you give him the code, why not try to improve it some es. 1 check length before StringBuilder, 2 why create afterRemove, ecc.. remove all else if else since it has return values.... will your at it teach him some nice code style..
@PetterFriberg I agree about point 1 (and hesitated to add it before you pointed it) but I think point 2 doesn't apply: for a beginner, I feel it is easier to read code like this than a long line chaining calls like new StringBuilder(str).delete(1, 4).toString();
Not just for a beginner. I often create "unnecessary" interim variables solely to make it more clear at a glance what the code is supposed to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.