bobjohnson
bobjohnson

Reputation: 19

How to add elements to a String but not reset it each time?

I am having some trouble with Strings in java. Below is a code that when given 2 numbers start and end it would return something like 1 + 2 + 3 + if start was 1 and end was 4. But my code (below) would only return 3 + . So how would I make it so that adds a new element to the string each time the for loop is run rather than resetting the whole thing?

String sumString = "";

        for (int i = start; i < end; i++) {  
            
            sumString = i + " + ";
        }

Upvotes: 1

Views: 68

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79550

i + " + "should be added to sumString and reassigned to sumString.

Replace

sumString = i + " + ";

with

sumString = sumString + i + " + ";

A shortcut to write it is as follows:

sumString += i + " + ";

Upvotes: 2

Shant Khayalian
Shant Khayalian

Reputation: 110

just simply add + in front of the =

public class Main {
    public static void main(String[] args) {
        String sumString = "";
        int start = 1;
        int end =4;
        for (int i = start; i < end; i++) {

            sumString += i + " + ";
        }
        System.out.println(sumString);
    }
}

Upvotes: 3

Related Questions