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".
-
4I hate to write this... But... What have you tried?Maroun– Maroun2013年03月30日 20:48:40 +00:00Commented Mar 30, 2013 at 20:48
-
1@MarounMaroun lol..Me too.. So Erkan what have you tried...?Vishal K– Vishal K2013年03月30日 20:52:49 +00:00Commented 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?justderb– justderb2013年03月30日 20:52:56 +00:00Commented Mar 30, 2013 at 20:52
-
1Maybe you don't want a StringBuilder, but a circular buffer?NilsH– NilsH2013年03月30日 20:54:14 +00:00Commented Mar 30, 2013 at 20:54
-
1Agree with @NilsH, this isn't StringBuilder, what you want is more of a character Queue.Taylor– Taylor2013年03月30日 20:56:59 +00:00Commented Mar 30, 2013 at 20:56
3 Answers 3
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);
Comments
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
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);
}
}