英文:
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("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);
答案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<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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论