I have been facing problems in passing array in java. The code is:
package input_output;
import static java.lang.System.out;
import java.util.Scanner;
public class InputOutput {
private static Scanner sc;
public static void main(String []args){
sc = new Scanner(System.in);
out.print("Enter the length of arrays :\t");
int n = sc.nextInt();
Employee[] emp = new Employee[n];
for(int i=0;i<n;i++){
out.print("\nEnter name and age of " + (i+1) + " employee :\t");
emp[i] = new Employee();
emp[i].setName(sc.nextLine());
sc.nextLine();
emp[i].setAge(sc.nextInt());
}
Operation operate = new Operation(emp,n);
operate.printOnScreen();
}
}
class Operation{
Employee []emp;
public Operation(Employee[] emp,int n){
this.emp=emp;
for(Employee e: this.emp)
e = new Employee();
}
public void printOnScreen() {
for(Employee e : emp){
e = new Employee();
out.println("Name:\t" + e.getName() + "\t\tAge:\t" + e.getAge() + "\n");
}
}
}
Employee class is a simple bean containing getter and setter methods of age and name.
The output is coming :
Name: null
Age:0
What's my mistake?
Now I have changed the constructor to
public Operation(Employee[] emp, int n){
this.emp=emp;
}
and removed the line:
e = new Employee();
from PrintOnScreen()
And the output is:
Name:
Age:21
for(Employee e: this.emp) e = new Employee();?Employeeclass so we can see whether the getter/setter is correctly implemented?