-2

Class File:

public class Student {

    public String stu_FName;
    public String stu_LName;
    public  String stu_ID;
}

This is the code I wrote to get inputs from the user public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter value for X");
        int x = sc.nextInt();
        ArrayList<Student> stuIDArray = new ArrayList<Student>(4);

        while (x != 0) {
            Student st = new Student();
            System.out.println("Enter First Name");
            st.stu_FName = sc.next();
            stuIDArray.add(st);
            System.out.println("Enter value fo1r X");
            x = sc.nextInt();

        }

When I print the size of the array after storing values using the above code, size works fine,

System.out.println(stuIDArray.size());

but when i try to print out the results in any of the following methods, it prints some code type format

for (int i=0;i<stuIDArray.size();i++){

    System.out.println(stuIDArray.get(i));
}

for (Student a : stuIDArray){
    System.out.println(a);
}

output :

com.company.Student@45ee12a7

com.company.Student@330bedb4

com.company.Student@45ee12a7

com.company.Student@330bedb4
m2j
  • 1,152
  • 5
  • 18
  • 43

3 Answers3

2

This would happen because when you are trying to print the student "object", it would print the string representation of the student object. What you need to do is to override the toString method in Student class with proper properties somewhat like,

@Override
public String toString() {
    return "Student [stu_FName=" + stu_FName + ", stu_LName=" + stu_LName
            + ", stu_ID=" + stu_ID + "]";
}
DNAj
  • 240
  • 3
  • 9
2

You have to learn about toString() method. When you try to use System.out.println() on an object, its toString() method is invoked, and the signature you've been getting, e.g. com.company.Student@330bedb4 is the default return value of those methods, as explained here. If you'd like a proper detail of each field, override the toString method in your Student class. For more, check out this answer

Community
  • 1
  • 1
buræquete
  • 14,226
  • 4
  • 44
  • 89
2

You need to specify name of the variable you need to get data for. Below code is working fine.

for (int i = 0; i < stuIDArray.size(); i++) {
    System.out.println(stuIDArray.get(i).stu_FName);
}

for (Class1 a : stuIDArray) {
    System.out.println(a.stu_FName);
}
buræquete
  • 14,226
  • 4
  • 44
  • 89
ManishPrajapati
  • 459
  • 1
  • 5
  • 16