简体   繁体   中英

Concatenation in java?

In PHP you can concatenate strings with .= so that the string grows with what ever you add to it. I wonder if this could be done in java? I made some test in this code, to add all number into one long string, but not working! Could it be done in some other way?

int number = 100;
for (int x = number; x <= 2; x--) {

    resultat = resultat + Integer.toString(x);
}

Yes, += in Java is .= in PHP:

result += Integer.toString(x) . You just need to define String resultat = "" above the loop. (And as others noted - fix your loop condition, it's always false)

However, in loops you'd better use a StringBuilder . A String is immutable, so every time you use + a new string is created (which may be inefficient with bigger loops). Instead:

StringBuilder builder = new StringBuilder();
for (...) {
    builder.append(x);
}
String result = builder.toString();

x <= 2 is never true for x = 100 ...

You have to change the condition to x >= 2

But you can use +=

Your for loop just needs a bit of work. You've currently got x <= 2 when it should be x >= 2 otherwise the loop will never run as 100 is never smaller than 2!

It doesn't work in your example because you got the terminating condition of the for loop wrong. You should write it like this:

String resultat = "";
int number = 100;
for (int x = number; x >= 2; x--) {
  resultat = resultat + Integer.toString(x);
}

A for loop is roughly a while loop with some little extras. That's why you have to write the condition like this.

Try to use StringBuilder.append like this

    int number = 100;
    StringBuilder builder = new StringBuilder();
    for (int x = number; x <= 2; x--) {
        builder.append(x);
    }
    String result = builder.toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM