Adding strings to lists - Java

55,219

Solution 1

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));
    }

Solution 2

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));
    }

Solution 3

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);
  }

Solution 4

Can't you do this?

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

Solution 5

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

Share:
55,219
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years
            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.