People类怎么定义的?下面的代码你看看有没有帮助。
import java.util.ArrayList;
import java.util.Collection;
import java.util.Scanner;
class People {
private String name;
private String sex;
private int age;
private int sid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String toString() {
return name +","+ sex+"," + age+"," + sid;
}
}
public class CollectionPeople {
static Collection<People> person = new ArrayList<People>();
// 初始化Collection
public void init() {
People p1 = new People();
p1.setName("刘建龙");
p1.setAge(24);
p1.setSex("男");
p1.setSid(881103);
person.add(p1);
People p2 = new People();
p2.setName("刘小龙");
p2.setAge(24);
p2.setSex("男");
p2.setSid(881106);
person.add(p2);
}
// 上为在类中定义一个集合,但是在存入成员时总是不成功,下为我写的存入成员的类,大家看看有什么要改的。在主方法中调用后,总是存储不成功。
public static void main(String[] args) {
People p = new People();
// 建立一个集合用于存放people的信息
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名");
String name = sc.nextLine();
p.setName(name);
System.out.println("请输入性别");
String sex = sc.nextLine();
p.setSex(sex);
System.out.println("请输入年龄");
int age = sc.nextInt();
p.setAge(age);
System.out.println("请输入数字代码");
int sid = sc.nextInt();
p.setSid(sid);
person.add(p);
System.out.println("添加成员成功!");
System.out.println(p);
}
} |