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".
4

3 回答 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);
于 2013-03-30T21:01:18.043 回答
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
于 2013-03-30T20:57:05.407 回答
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);

  }
}
于 2013-03-30T20:58:51.113 回答