Xlayton
Xlayton

Reputation: 1

StringBuffer not outputting what I expected

I am trying to switch a $ within a string with the character to its right. I am not allowed to use a char[], so I decided to use StringBuffer. However, when I try to run the code with something like H$E it outputs HE$H$E I have no idea where the extra characters are coming from, and I am seeking an explanation.

package schrumpf.clayton.csc110.drills1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MoneyToTheRight {

static BufferedReader in;


public static void main(String[] args) throws IOException{
    in = new BufferedReader(new InputStreamReader(System.in));

    String input = in.readLine();
    int dollarIndex = input.indexOf("$");
    StringBuffer buffer =  new StringBuffer(input);
    char afterDollarChar = buffer.append(input).charAt((dollarIndex + 1));
    buffer.setCharAt(dollarIndex, afterDollarChar);
    buffer.setCharAt((dollarIndex + 1),'$');
    String result = buffer.toString();
    System.out.println(result);
    }

}

Upvotes: 0

Views: 248

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533530

You are adding the input twice.

StringBuffer buffer =  new StringBuffer(input);
buffer.append(input)

I suggest adding it once. I also suggest using StringBuilder which replaced StringBuffer more than ten years ago.

Scanner in = new Scanner(System.in);

StringBuilder buffer =  new StringBuilder(in.nextLine());
int dollarIndex = buffer.indexOf("$");
buffer.setCharAt(dollarIndex, buffer.charAt(dollarIndex + 1));
buffer.setCharAt(dollarIndex + 1, '$');
System.out.println(buffer);

or as a one-liner

System.out.println(in.nextLine().replaceFirst("\\$(.)", "$1\\$"));

Upvotes: 2

Related Questions