I would like display the values of my String array in one Jlabel.
I've tried with a loop (for) but, the result is the new letter overwrites the previous.
I do not understand how I could displaying the letters following.
labelWord is the variableName of my Jlabel.
String myArray[] = new String[4];
myArray[0] = "h";
myArray[1] = "e";
myArray[2] = "l";
myArray[3] = "l";
myArray[4] = "o";
and my loop :
for (int j = 0; j <= myArray.length; j++) {
labelWord.setText(myArray[j]);
}
You are replacing the text each time you call labelWord.setText().
Just build the whole string before you set it
StringBuilder builder = new StringBuilder();
for (int j = 0; j <= myArray.length; j++) {
builder.append(myArray[j]);
}
labelWord.setText(builder.toString());
Your code does not work because you set the label value with the 1st String, then the second one, then the 3rd one... You need to concatene all your String into one then set the label text with this value:
String value ="";
for (int j = 0; j <= myArray.length; j++) {
value += myArray[j];}
labelWord.setText( value );
Note: you can also use a StringBuilder instead of concatenating directly to the String.
You are overwriting it yourself by calling setText() everytime in loop. you need to append it to the text by doing:
labelWord.setText(labelWord.getText() + myArray[j]);
Hope this helps.
The easiest way to do this without using StringBuilder or anything like that would be to use another string variable
String myLabelText = "";
for (int j = 0; j <= myArray.length; j++) {
myLabelText = myLabelText + myArray[j];
}
labelWord.setText( myLabelText );
You were essentially just changing the value of the label for every item in the array, not adding it to the end
One More Interesting Way you would like to know(In your CASE)
String arr[]={"h","e","l","l","o"};
System.out.println(Arrays.toString(arr).replaceAll("[\\]\\[,\\s]", ""));
OUTPUT
hello
So directly,
jlabel.setText(Arrays.toString(arr).replaceAll("[\\]\\[,\\s]", ""));
NOTE:
This will not be applicable if array elements contains space(Sorry for that).
Related
ArrayList<String> gradeN = new ArrayList<String>();
gradeN.add("one");
gradeN.add("two");
int num2 = 0;
while (num<5){
gradeN.get(0).concat("*");
num2++;
}
System.out.println(gradeN.get(0));
This is not working.
I want output like this:
one*****
and do this in a loop..
There are 2 mistakes in your code:
The variable incremented in your while loop is different to the one used in the condition.
Strings are immutable. String.concat returns a different String object and does not modify the original String. That means the value in your List is not modified. To fix this, use List.set to replace the old value in the list with a new one.
int num2 = 0;
while (num2 < 5) {
String newValue = gradeN.get(0).concat("*");
gradeN.set(0, newValue);
num2++;
}
Your question is somewhat unclear. Do you always want to add 5 stars to the string? If so, a constant string with 5 stars in it makes more sense than a loop. And I assume you really meant to do this for every element of gradeN? So something like this:
ArrayList<String> gradeN = new ArrayList<String>();
gradeN.add("one");
gradeN.add("two");
for (int i = 0; i < gradeN.size(); i++) {
gradeN.set(i, gradeN.get(i) + "*****");
System.out.println(gradeN.get(i));
}
If the number of stars added may vary and you really wanted to append them in a loop, then you could use StringBuilder to build it up:
ArrayList<String> gradeN = new ArrayList<String>();
gradeN.add("one");
gradeN.add("two");
int num = 5;
for (int i = 0; i < gradeN.size(); i++) {
StringBuilder stars = new StringBuilder(gradeN.get(i));
for (int j = 0; j < num; j++) {
stars.append('*');
}
gradeN.set(i, stars.toString());
System.out.println(gradeN.get(i));
}
One solution is to get the value of gradeN.get(0) on every loop and append * to it.
i.e.:
int num2 = 0;
while (num2<5){
gradeN.set(0, gradeN.get(0)+"*");
num2++;}
Output:
one*****
Demo:
http://ideone.com/XQvWqX
I have a string that contains numbers like: 02101403101303101303140
how can I iterate the string to check whether the number in string is >= 2 and remember that number's index in array or list for further processing?
the further processing should be replacing substrings.
for example: the iterator found number 2 and remembers the index of this character.
Now it takes the next character from 2 and remembers this character index also.
Now it is possible to replace the substring.
Let's say there is 21. Now I want this to become 11
Or lets say there is 60, this should be replaced with 000000.
First number is indicator of "how many" and the second number is "what".
Or is there a better way to remember and replace certain substrings in that way?
Thank you in advance.
There you go. but remember to atleast try next time
String str = "02101403101303101303140";
StringBuilder sb = new StringBuilder();
for(int i=0; i < str.length(); i+=2)
for(int j =0; j < Integer.parseInt(String.valueOf(str.charAt(i))); j++)
sb.append(str.charAt(i+1));
System.out.print(sb.toString());
Not sure if I'm understanding well your question, you could try something like this:
String mystring = "02101403101303101303140";
String target = "21";
String replacement = "11"
String newString = mystring.replace(target, replacement);
String str = "02101403101303101303140";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if(Integer.parseInt(String.valueOf(str.charAt(i))) >= 2) {
int temp = Integer.parseInt(String.valueOf(str.charAt(i))) - 1;
for (int j = 0; j < temp ; j++) {
sb.append(str.charAt(i+1));
}
}
else {
sb.append(str.charAt(i));
}
}
System.out.println(sb.toString());
This would produce: 01101000011101000111010001110000 which is binary for "http" (without quotes).
Thank you all! What I really needed was a push to right direction and thank zubergu for that. Also fr34k gave the best answer!
Hello I am having trouble implementing this function
Function:
Decompress the String s. Character in the string is preceded by a number. The number tells you how many times to repeat the letter. return a new string.
"3d1v0m" becomes "dddv"
I realize my code is incorrect thus far. I am unsure on how to fix it.
My code thus far is :
int start = 0;
for(int j = 0; j < s.length(); j++){
if (s.isDigit(charAt(s.indexOf(j)) == true){
Integer.parseInt(s.substring(0, s.index(j))
Assuming the input is in correct format, the following can be a simple code using for loop. Of course this is not a stylish code and you may write more concise and functional style code using Commons Lang or Guava.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < s.length(); i += 2) {
final int n = Character.getNumericValue(s.charAt(i));
for (int j = 0; j < n; j++) {
builder.append(s.charAt(i + 1));
}
}
System.out.println(builder.toString());
Here is a solution you may like to use that uses Regex:
String query = "3d1v0m";
StringBuilder result = new StringBuilder();
String[] digitsA = query.split("\\D+");
String[] letterA = query.split("[0-9]+");
for (int arrIndex = 0; arrIndex < digitsA.length; arrIndex++)
{
for (int count = 0; count < Integer.parseInt(digitsA[arrIndex]); count++)
{
result.append(letterA[arrIndex + 1]);
}
}
System.out.println(result);
Output
dddv
This solution is scalable to support more than 1 digit numbers and more than 1 letter patterns.
i.e.
Input
3vs1a10m
Output
vsvsvsammmmmmmmmm
Though Nami's answer is terse and good. I'm still adding my solution for variety, built as a static method, which does not use a nested For loop, instead, it uses a While loop. And, it requires that the input string has even number of characters and every odd positioned character in the compressed string is a number.
public static String decompress_string(String compressed_string)
{
String decompressed_string = "";
for(int i=0; i<compressed_string.length(); i = i+2) //Skip by 2 characters in the compressed string
{
if(compressed_string.substring(i, i+1).matches("\\d")) //Check for a number at odd positions
{
int reps = Integer.parseInt(compressed_string.substring(i, i+1)); //Take the first number
String character = compressed_string.substring(i+1, i+2); //Take the next character in sequence
int count = 1;
while(count<=reps)//check if at least one repetition is required
{
decompressed_string = decompressed_string + character; //append the character to end of string
count++;
};
}
else
{
//In case the first character of the code pair is not a number
//Or when the string has uneven number of characters
return("Incorrect compressed string!!");
}
}
return decompressed_string;
}
I'm taking care of some other methods and I don't know what to do with this one. I want to change the order of the string inside the array (not the order of the string*s*), but this isn't accepted. Any ideas?
public void invert() {
for(int i = 0; i < array.length; i++){
for(int j = 0, k = array[i].length() - 1; j < k; j++, k--){
char a = array[i].charAt(j);
array[i].charAt(j) = array[k].charAt(k); //ERROR HERE
array[i].charAt(k) = a; //AND HERE
}
}
}
EDIT: I'll leave here what I mean.
I have an array = {"Hello", "Goodbye"}
I want to change it to {"olleH", "eybdooG"}
Java string are immutable. You can't change them.
(But you can convert the string to a StringBuilder - http://docs.oracle.com/javase/tutorial/java/data/buffers.html - which is essentialy a mutable string, change the characters, and then convert the StrignBuilder back to String.)
Try this code (I haven't tested it, but I hope it works):
for(int i = 0; i < array.length; i++) {
StringBuilder b = new StringBuilder(array[i]);
for(int j = 0, k = b.length() - 1; j < k; j++, k--){
char a = b.charAt(j);
b.setCharAt(j, array[k].charAt(k));
b.setCharAt(k, a);
}
array[i] = b.toString();
}
array[i].charAt(j) = array[k].charAt(k); //ERROR HERE
array[i].charAt(a) returns a value not a variable. You are trying to assign a value to a value which doesn't make any sense.
java String is immutable. You can't change it.
Use StringBuilder which has setCharAt(int index,
char ch); function which is what you are probably wanting.
The most simple way is, to reverse letter with StringBuilder.reverse() method. Try,
for(String str : array){
System.out.println(new StringBuilder(str).reverse());
}
Just use this on every String in your array:
String reversed = new StringBuilder(stringFromArray).reverse().toString();
try doing new StringBuilder(array[i]).reverse().toString();
you would have to create a substring.
array[i]= array[i].substring(0,j) + array[k].charAt(k) + array[i].substring(j+1);
This would do the required edit i beleive
Suppose some situations exist where you would like to increment and decrement values in the same for loop. In this set of situations, there are some cases where you can "cheat" this by taking advantage of the nature of the situation -- for example, reversing a string.
Because of the nature of building strings, we don't really have to manipulate the iterate or add an additional counter:
public static void stringReversal(){
String str = "Banana";
String forwardStr = new String();
String backwardStr = new String();
for(int i = str.length()-1; i >= 0; i--){
forwardStr = str.charAt(i)+forwardStr;
backwardStr = backwardStr+str.charAt(i);
}
System.out.println("Forward String: "+forwardStr);
System.out.println("Backward String: "+backwardStr);
}
However, suppose a different case exists where we just want to print a decremented value, from the initial value to 0, and an incremented value, from 0 to the initial value.
public static void incrementAndDecrement(){
int counter = 0;
for(int i = 10; i >= 0; i--){
System.out.println(i);
System.out.println(counter);
counter++;
}
}
This works well enough, but having to create a second counter to increment seems messy. Are there any mathematical tricks or tricks involving the for loop that could be used that would make counter redundant?
Well it looks like you just want:
for(int i = 10; i >= 0; i--){
System.out.println(i);
System.out.println(10 - i);
}
Is that the case? Personally I'd normally write this as an increasing loop, as I find it easier to think about that:
for (int i = 0; i <= 10; i++) {
System.out.println(10 - i);
System.out.println(i);
}
Note that your string example is really inefficient, by the way - far more so than introducing an extra variable. Given that you know the lengths involved to start with, you can just start with two char[] of the right size, and populate the right index each time. Then create a string from each afterwards. Again, I'd do this with an increasing loop:
char[] forwardChars = new char[str.length()];
char[] reverseChars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
forwardChars[i] = str.charAt(i);
reverseChars[reverseChars.length - i - 1] = str.charAt(i);
}
String forwardString = new String(forwardChars);
String reverseString = new String(reverseChars);
(Of course forwardString will just be equal to str in this case anyway...)
You can have multiple variables and incrementers in a for loop.
for(int i = 10, j = 0; i >= 0; i--, j++) {
System.out.println(i);
System.out.println(j);
}