将项目添加到类变量的列表中

huangapple go评论70阅读模式
英文:

add items to a list from class variable

问题

我创建了一个名为Test的类,具有(名字和姓氏变量),以及getter和setter方法,然后我创建了一个Test类型的List。我使用set方法设置变量的值,然后尝试将klass.setName(nminput)klass.setSurname(surnminput)添加到List中,但即使使用循环,只有一个值被添加进去。有没有办法从类变量将项目添加到List中?

Scanner input = new Scanner(System.in);
Test klass = new Test("name", "surname");
List<Test> list = new ArrayList<>();

for (int i = 0; i < 3; i++) {
    String nminput = input.next();
    String surnminput = input.next();
    klass.setName(nminput);
    klass.setSurname(surnminput);
    list.add(klass);
    i++;
}
System.out.println(list);
英文:

I have created a class named Test with (name and surname variables) plus getter and setter, then I made a List with Test type. I use set method to set variables value and then I try to add klass.setName(nminput) and klass.setSurname(surnminput); to the List but only one value being added even with loops. Is there anyway to add item to a List from class variable?

Scanner input = new Scanner(System.in);
Test klass = new Test(&quot;name&quot;, &quot;surname&quot;);
List &lt; Test &gt; list = new ArrayList &lt; &gt; ();

for (int i = 0; i &lt; 3; i++) {
    String nminput = input.next();
    String surnminput = input.next();
    klass.setName(nminput);
    klass.setSurname(surnminput);
    list.add(klass);
    i++;
}
System.out.println(list);

答案1

得分: 0

代替反复更改相同Test对象的值(它被称为Klass),您希望在循环内部创建多个Test对象。

Scanner input = new Scanner(System.in);
List<Test> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
    String nminput = input.next();
    String surnminput = input.next();
    Test klass = new Test(nminput, surnminput);
    list.add(klass);
    i++;
}
System.out.println(list);
英文:

Instead of changing the value for the same Test object (it's called Klass) again and again you want to create multiple Test objects inside you're loop.

Scanner input = new Scanner(System.in);
List&lt;Test&gt; list = new ArrayList&lt;&gt;();
for (int i = 0; i &lt; 3; i++) {
    String nminput = input.next();
    String surnminput = input.next();
    Test klass = new Test(nminput, surnminput);
    list.add(klass);
    i++;
}
    System.out.println(list);

huangapple
  • 本文由 发表于 2020年10月6日 06:25:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64217003.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定