MrB
MrB

Reputation: 818

Performing addition when creating a string

I'm creating a number of objects with details read in from an array. They will have a standard format for one of their instance variables which I'd like to be, in part, an ascending number. Specifically, I'm creating a load of Location objects which I'd like to have a description of "Flat 1", "Flat 2", etc.

I'm wondering though if there is an easy way to perform addition when assigning a value to a String. Stripped down to the relevant part, my code is:

int size = locations.size();
Location l;
for (int i=0; i<size; i++){
    l = new Location ("Flat " + i + 1); //LINE A
    addLocation(l);
}
//several bits of code have been removed and swapped around here, I realise 
//that that snippet doesn't really perform anything useful

However, Java interprets both the "+" symbols in LINE A as concatenation meaning I get "Flat 01", "Flat 11", "Flat 21", etc.

Obviously I could change around the way the loop works, but I was curious as to whether performing calculations in a myString = value + 2 type statement was possible?

Upvotes: 2

Views: 78

Answers (2)

Jacob G.
Jacob G.

Reputation: 29680

String concatenation is left-associative, so all you have to do is wrap the value you want in parentheses to ensure that it's calculated first:

l = new Location ("Flat " + i + 1);

is effectively:

l = new Location (("Flat " + i) + 1);

So i is appended to the string "Flat " first; and then 1 is appended to that.

Should be:

l = new Location ("Flat " + (i + 1));

Upvotes: 4

Andi
Andi

Reputation: 476

Use parentheses:

l = new Location ("Flat " + (i + 1)); //LINE A

Upvotes: 3

Related Questions