mike
mike

Reputation: 61

Adding strings to lists - Java

        String t1 = request.getParameter("t1");
        String t2 = request.getParameter("t2");

        List<String> terms = new ArrayList<String>();
        for (int i = 1; i < 51; i++) {
            terms.add(t + i);
        }

Imagine I had vars t1 to t50, is it possible to loop each t using a counter? Something like above, but obvi that doesn't work.

Upvotes: 6

Views: 71588

Answers (6)

Vincent Koeman
Vincent Koeman

Reputation: 751

You cannot simply loop over variables. However, why don't you make t an array (string[]), or even an ArrayList if you do not know the size in advance. Then you wouldn't even need a loop, and you can access all variables in almost the same way?!

Upvotes: 0

jzd
jzd

Reputation: 23629

Instead of all the temp single variables just grab the parameters in a loop:

    List<String> terms = new ArrayList<String>();
    for (int i = 1; i < 51; i++) {
        terms.add(request.getParameter("t"+ i));
    }

Upvotes: 5

wjans
wjans

Reputation: 10115

Can't you do this?

for (int i = 1; i < 51; i++) {
    terms.add(request.getParameter("t" + i));
}

Upvotes: 3

Joachim Sauer
Joachim Sauer

Reputation: 308031

No, you can't "construct" variable names like that in Java (in fact, at runtime local variables don't even have any names).

You can, however, get rid of the variables entirely and call getParameter() with the appropriate values:

  List<String> terms = new ArrayList<String>();
  for (int i = 1; i < 51; i++) {
      terms.add(request.getParameter("t" + i);
  }

Upvotes: 5

Bozho
Bozho

Reputation: 597106

terms.add(request.getParameter("t" + i));

In your code you are adding to the list a string that is a non-existent variable t contatenated / summed with i

Upvotes: 1

highlycaffeinated
highlycaffeinated

Reputation: 19867

You don't need the temporary variables, t1, t2, etc. Otherwise you were on the right track.

    List<String> terms = new ArrayList<String>();
    for (int i = 1; i < 51; i++) {
        terms.add(request.getParameter("t" + i));
    }

Upvotes: 13

Related Questions