添加学生对象并遍历

package ArrayList;
public class Stuent {
    //1.私有化成员变量
    //2.空参构造方法
    //3.带全部参数的构造方法
    //4.get/set方法
    private String name;
    private int age;
    public Stuent(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Stuent() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
package ArrayList;
import java.util.ArrayList;
public class Test4 {
    public static void main(String[] args) {
      //1.创建集合
        ArrayList list=new ArrayList<>();
        //2.创建学生对象
        Stuent s1=new Stuent("karry",24);
        Stuent s2=new Stuent("jackson",23);
        Stuent s3=new Stuent("roy",23);
        //3.添加元素
        list.add(s1);
        list.add(s2);
        list.add(s3);
//4.遍历集合
        for (int i = 0; i < list.size(); i++) {
           //i 索引  list.get(i)元素/学生对象
            Stuent stu = list.get(i);
            System.out.println(stu.getName()+","+stu.getAge());
        }
    }
}
package ArrayList;
public class Stuent {
    //1.私有化成员变量
    //2.空参构造方法
    //3.带全部参数的构造方法
    //4.get/set方法
    private String name;
    private int age;
    public Stuent(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Stuent() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
package ArrayList;
import java.util.ArrayList;
import java.util.Scanner;
public class Test5 {
    public static void main(String[] args) {
        //1.创建集合
        ArrayList list=new ArrayList();
        //2.键盘录入学生的信息
        Scanner sc=new Scanner(System.in);
        for (int i = 0; i < 3; i++) {
            Stuent s=new Stuent();
            System.out.println("请输入学生的姓名");
           String name= sc.next();
            System.out.println("请输入学生的年龄");
            int age = sc.nextInt();
           //把name和age赋值给学生
            s.setAge(age);
            s.setName(name);
            //把学生对象添加到集合当中
            list.add(s);
        }
        //3.遍历
        for (int i = 0; i < list.size(); i++) {
           Stuent stu=list.get(i) ;
            System.out.println(stu.getName()+","+stu.getAge());
        }
    }
}

你可能感兴趣的:(java,windows,开发语言)