简体   繁体   English

将字符串添加到列表 - Java

[英]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?想象一下,我有 vars t1 到 t50,是否可以使用计数器循环每个 t? Something like above, but obvi that doesn't work.类似上面的东西,但 obvi 不起作用。

You don't need the temporary variables, t1, t2, etc. Otherwise you were on the right track.您不需要临时变量 t1、t2 等。否则您就走在了正确的轨道上。

    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).不,您不能像 Java 中那样“构造”变量名称(实际上,在运行时局部变量甚至没有任何名称)。

You can, however, get rid of the variables entirely and call getParameter() with the appropriate values:但是,您可以完全摆脱变量并使用适当的值调用getParameter()

  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在您的代码中,您正在向列表中添加一个字符串,该字符串是一个不存在的变量t包含/与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.但是,如果您事先不知道大小,为什么不制作一个数组 (string[]),甚至是 ArrayList。 Then you wouldn't even need a loop, and you can access all variables in almost the same way?!那么您甚至不需要循环,并且可以以几乎相同的方式访问所有变量?!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM