【问题标题】:adding multiple objects to ArrayList is not printing very well向 ArrayList 添加多个对象打印效果不佳
【发布时间】:2020-08-26 06:02:15
【问题描述】:
import java.util.ArrayList;
import java.util.Scanner;

public class Student {
    static String studentNum;
    static int age;
    static String Name;
    
    Student(int Age, String Name){
        this.Name = Name;
        this.age = Age;
    }
    
    public static String input_read() {
        Scanner sc = new Scanner(System.in);
        if (sc.hasNext()) {
            studentNum = sc.next();
        } else {
            sc.close();
        }
        return studentNum;
    }
    
    public static int setAge() {
        System.out.println("Enter the age of the Student");
        return Integer.valueOf(input_read());
    }
    
    public static String setName() {
        System.out.println("Enter the name of the Student");
        return input_read();
    }
    
    public static int getAge() {
        return age;
    }
    public static String getName() {
        return Name;
    }

    public static void main(String[] args) {
        ArrayList<Student> ar = new ArrayList();
        for (int i=0; i<2; i++) {
            Student s1= new Student(setAge(), setName());
            ar.add(s1);
        }
        for (Student each :ar){
            
            System.out.println(each.getName());
            System.out.println(each.getAge());
        }
    }

}

我是 Java 新手。我创建了一个程序来添加学生的年龄和姓名。该程序输出仅打印最后一个对象 2 次。它没有打印列表中的所有对象。有人知道为什么吗?

【问题讨论】:

  • 你需要了解静态成员和实例成员的区别和

标签: java arraylist collections


【解决方案1】:

您应该从成员变量中删除关键字static

这导致它们在所有实例之间共享。

请看这里:What does the 'static' keyword do in a class?

【讨论】:

    猜你喜欢
    • 2016-06-28
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2015-05-26
    相关资源
    最近更新 更多