2

I have 3 buttons: "Q", "W" and "E". When clicked they should append their letter to a StringBuilder. Like this:

StringBuilder s = new StringBuilder();

(When "Q" button is clicked):

s.append("q");

(When "W" button clicked):

s.append("w");

But what I want is to have a maximum of 3 characters to be in the StringBuilder. 3 digits after reaching the initial character of a key is pressed at the end wiper and write a new one. After the StringBuilder reaches three characters, it will remove the initial one and append the next. Like marquee. Example:

StringBuilder is "QWW",
When E button clicked StringBuilder must be "WWE".
When W button clicked StringBuilder must be "WEW".
6
  • 4
    I hate to write this... But... What have you tried? Commented Mar 30, 2013 at 20:48
  • 1
    @MarounMaroun lol..Me too.. So Erkan what have you tried...? Commented Mar 30, 2013 at 20:52
  • Adding to @MarounMaroun, do you have sample code you have written so that we can help you fix this problem? Commented Mar 30, 2013 at 20:52
  • 1
    Maybe you don't want a StringBuilder, but a circular buffer? Commented Mar 30, 2013 at 20:54
  • 1
    Agree with @NilsH, this isn't StringBuilder, what you want is more of a character Queue. Commented Mar 30, 2013 at 20:56

3 Answers 3

1

The alternative way is to use char array

char[] arr = new char[]{'','',''};
...
private void appendChar(char a){
  for(int i=0;i<arr.length-1;i++){
    arr[i] = arr[i+1];
  }
  arr[arr.length-1] = a;
}

And finally:

String res = new String(arr);
Sign up to request clarification or add additional context in comments.

Comments

0

Use StringBuilder#deleteCharAt(int index):

public static void addToStringBuilder(StringBuilder sb, int max, char letter)
{
    if(sb.length() >= max) sb.deleteCharAt(0);
    sb.append(letter);
}

For example:

StringBuilder sb = new StringBuilder();
addToStringBuilder(sb, 3, 'Q');
System.out.println(sb);
addToStringBuilder(sb, 3, 'W');
System.out.println(sb);
addToStringBuilder(sb, 3, 'W');
System.out.println(sb);
addToStringBuilder(sb, 3, 'E');
System.out.println(sb);
addToStringBuilder(sb, 3, 'W');
System.out.println(sb);

OUTPUT:

Q
QW
QWW
WWE
WEW

Comments

0

Here you go:

StringBuilder sBuilder = new StringBuilder();
public void prepareBuilder(String str)
{
  if (sBuilder.length() < 3)
  sBuilder.append(str);
  else 
  {
    sBuilder.deleteCharAt(0);
    sBuilder.append(str);

  }
}

Comments

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.