Click here to Skip to main content
15,905,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Basically, in this program,
we took 1 class i.e employee
and 2 methods - 1 for input and other one for display.

But here I do want display the displayinfo uniquely,
but instead the last record is getting printed based on the number...

I do know the reason, but can I get that unique output-
can it be done without an array!!
or how ??

What I have tried:

Java
<pre>import java.util.*;
class employee
{
int id;
String name;
int salary;
void info(){
Scanner obj = new Scanner(System.in);
System.out.println("Enter the id ??");
id = obj.nextInt();
System.out.println("Enter the name ??");
name = obj.next();
System.out.println("Enter the salary ??");
salary = obj.nextInt();
}
void displayinfo(){
System.out.println(" "+id+"  "+name+"  "+salary); 
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of records u want to enter ??");
int num = sc.nextInt();
employee a = new employee();
for(int i=0;i<num;i++){
	a.info();
	}
for(int j=0;j<num;j++){
	a.displayinfo();
	}
    }
}



Myoutput -
```
Enter the no. of records u want to enter ??
3
Enter the id ??
1
Enter the name ??
sdfsd
Enter the salary ??
34234
Enter the id ??
2
Enter the name ??
dfgdfg
Enter the salary ??
456456
Enter the id ??
3
Enter the name ??
thrytr
Enter the salary ??
53413
3 thrytr 53413
3 thrytr 53413
3 thrytr 53413
```
Posted
Updated 5-Jul-22 4:55am

1 solution

The problem is that you only have one employee object:
Java
int num = sc.nextInt();
employee a = new employee();
for(int i=0;i<num;i++){
	a.info();
}
for(int j=0;j<num;j++){
	a.displayinfo();
}

It does not matter how many times the first loop runs you will only have the information of the last set of data entered, since you overwrite it each time round. You need to create a List or Array to hold each employee's details as you enter them.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900