0

I have wrote the first class and declare all the variables and methods(get and set method). in class two I have created an array object but its not working properly, may be I did a mistake in somewhere, so can anyone just help me with that, please.

#Class 1

package com.javaArray;

public class ArrayOfObject {

private String fName;
private String lName;

public String getfName() {
    return fName;
}
public String getlName() {
    return lName;
}

public void setlName(String lName) {
    this.lName = lName;
}
public void setfName(String fName) {
    this.fName = fName;
}

}

#Class 2

package com.javaArray;

import java.util.Scanner;

public class Person {
    public static void main(String[] args) {
         ArrayOfObject[] arr = new ArrayOfObject[5];
         Scanner sc = new Scanner(System.in);

         for(int i=0;i<arr.length;i++){
        System.out.println("Enter First Name");
        arr[i].setfName(sc.next());
        System.out.println();
        System.out.println("Enter Last Name");
        arr[i].setlName(sc.next());
        System.out.println();
    }

    System.out.println("Persons name are:");

    for(int i=0;i<arr.length;i++){
        System.out.println(arr[i].getfName()+" "+arr[i].getlName());
    }
}

}

2 Answers2

2

ArrayOfObject[] arr = new ArrayOfObject[5];

In this step you just initialize your Array NOT your object inside it.

So in each step, you must init each of your object by doing this:

for (int i = 0; i < arr.length; i++) {    
    arr[i] = new ArrayOfObject();
    System.out.println("Enter First Name");
    ...
Brian H.
  • 1,603
  • 11
  • 16
  • I got it. Thank you brother. This was my first question ever in Stack Overflow and You have answered my question within a minute. Thanks a lot. – Shahajahan Ahamed Jun 23 '20 at 07:12
  • You're welcome :) Because this is a common mistake of a new people in `Java` :) So just keep studying and enjoy coding, brother :) – Brian H. Jun 23 '20 at 07:18
0

First of all, there is no need for getters and setter and all additional code. You can use library Lombok, so you dont need to write a lot of code. so your first class should look like:

@Data
public class ArrayOfObject {

private String fName;
private String lName;

}

Second thing for Class2 you can reffer to: Reading in from System.in - Java if I got your question right.

  • It's `@Getter` and `@Setter` (without s). Also, `@Data` implies `@Getter` and `@Setter`, so the latter two can be omitted. – MC Emperor Jun 23 '20 at 07:21