简体   繁体   中英

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.

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

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

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

Can't you do this?

for (int i = 1; i < 51; i++) {
    terms.add(request.getParameter("t" + i));
}
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

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?!

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