1
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());
        }
    }

}

I am new guy in Java. I created a program to add student age and name. This program output is printing only last object 2 times. It is not printing all the objects in the list. Anybody know why?

Holger
  • 285,553
  • 42
  • 434
  • 765

1 Answers1

2

You should remove the keyword static from your member variables.

That is causing them to be shared across all instances.

See here: What does the 'static' keyword do in a class?

Patrick Parker
  • 4,863
  • 4
  • 19
  • 51