I have an Employee class with one method named addEmployee which manipulates an ArrayList to add employees. My following code won't print the list on the console screen. I can't find out what's wrong with my code.
package com.sib.Tmanager;
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
private String EmpFName;
private String EmpLName;
public Employee(String empFName, String empLName) {
super();
EmpFName = empFName;
EmpLName = empLName;
}
public String getEmpFName() {
return EmpFName;
}
public void setEmpFName(String empFName) {
EmpFName = empFName;
}
public String getEmpLName() {
return EmpLName;
}
public void setEmpLName(String empLName) {
EmpLName = empLName;
}
public static void addEmployee()
{
ArrayList<Employee> Emplist= new ArrayList<Employee>();
Scanner s=new Scanner(System.in) ;
System.out.println("Enter the Firstname of the employee");
String Fname= s.next();
System.out.println("Enter the Lastname of the employee");
String Lname= s.next();
Employee emp = new Employee(Fname, Lname);
Emplist.add(emp);
//System.out.println(emp.EmpFName +" "+ emp.EmpLName);
System.out.println(Emplist);
}
}
I tried to change my code by overriding the ToString() method and I still have the same following output.
Enter employee's Firstname
jason
Enter employee's Lastname
karl
[com.sib.Tmanager.Employee#1a758cb]
This may not be an answer, but a bit of advice about class design.
Think about an Employee as a physical object.
Should an Employee have a first name? Yes.
Should an Employee have a last name? Yes.
Should an Employee be filled with other Employyes? Absolutley not.
If the above third point doesn't make sense, what should you do?
Create a class called something like EmployeeList. Should an EmplpoyeeList have Employees? Why, of course!
The above class is the class you want to have the Employee ArrayList
Also, this is where you want to have the addEmployee method, so you can add the Employee the EmployeeList
Here's a example
public class EmployeeList {
ArrayList<Employee> employees;
public EmployeeList() {
employees = new ArrayList<Employee>();
}
public void addEmployee(Employee employee) {
employees.add(employee);
}
public void printEmployees() {
for (Employee e : employees) {
System.out.println(e);
}
}
}
So in the main, you first will create an EmployeeList then add Employees to it.
public static void main(String[] args) {
EmployeeList list = new EmployeeList();
list.addEmployee(new Employee("Jim", "Bo");
list.addEmployee(new Employee("Foo", "Bar");
list.addEmployee(new Employee("First", "Last");
list.printEmployees();
}
Note: to get the Employee object to print out as String representation, you should override the toString() method as others have suggested.
You can use Arrays.toString(empList.toArray(new Employee[0])) or empList.toString() in order to print the contents of an ArrayList. This will print nicely if you override toString() in Employee.
call AddEmployee() from public static void main()
System.out.println(Emplist)
you are trying to print Emplist object
you have to iterate the arraylist to show it's content
You should assign the ArrayList in the class fields and initialize it in the Constructor
public class Employee {
private String EmpFName;
private String EmpLName;
private ArrayList<Employee> Emplist;
.
.
.
}
public Employee(String empFName, String empLName) {
super();
ArrayList<Employee> Emplist= new ArrayList<Employee>();
EmpFName = empFName;
EmpLName = empLName;
}
Now when you need to add you only do :
this.Emplist.add(x);
in the addEmployee method
Related
As the tittle says i want to save each new created object of Person's name in a list:
This is my code so far
package javaapplication4;
import java.util.*;
public class Person {
private String namePerson;
static List personList = new ArrayList();
{
personList.add(getPersonName());
}
public Person(String namePerson){
this.namePerson = namePerson;
}
public void setPersonName(String namePerson){
this.namePerson = namePerson;
}
public String getPersonName(){
return namePerson;
}
public void setPersonList(List personList){
this.personList= personList;
}
public static List getPersonList(){
return personList;
}
each time i am creating a person object its gets added as a 'null' spot in the list (when i use println).
how i change that to the name of the new object Person
like
Person Guy = new Person("NameOfGuy"); then list must be [NameOfGuy].
{
personList.add(getPersonName());
}
The above is called an instance initializer. It is executed before the constructor is executed. At that time, getPersonName will return null as you haven't yet set the value of namePerson.
Move that inside the constructor
public Person(String namePerson){
this.namePerson = namePerson;
this.personList.add(namePerson);
}
Sidenote: It is a bad practice to use raw types. You are using a raw List. It must be as
List<String> personList = new ArrayList<>();
What is a raw type and why shouldn't we use it?
As pointed out by #user7, you are adding the name into the list at the wrong place. What you should be doing is, adding person's name into list while you are creating person's object, i.e. inside your constructor. Replace your constructor with this :
public Person(String namePerson){
this.namePerson = namePerson;
personList.add(namePerson);
}
You can do the job Doing below changes to the Person class:
import java.util.*;
public class Person {
private String namePerson;
static List<String> personList = new ArrayList<>();
public Person(String namePerson) {
this.namePerson = namePerson;
personList.add(this.namePerson);
}
public void setPersonName(String namePerson) {
this.namePerson = namePerson;
}
public String getPersonName() {
return namePerson;
}
public void setPersonList(List personList) {
this.personList = personList;
}
public static List getPersonList() {
return personList;
}
}
I am trying to create a method in my code that searches through an array list (in my case customerList, which contains Customer objects) and will add something new to it if that something isn't found in the ArrayList...
Here is how I have it all set up....
public class CustomerDatabase {
private ArrayList <Customer> customerList = null;
public CustomerDatabase() {
customerList = new ArrayList<Customer>();
}
and this is the method I'm trying to make. I'm trying to get it so that it will add a Customer with given name "n" to the end of the ArrayList if it isn't found in the ArrayList...
public void addCustomer(String n)
{
for(Customer c:customerList)
if (!customerList.contains(n))
customerList.add(n);
}
I'm aware that something is wrong with the whole .add and then a String thing but I'm not sure where I went wrong. Any input would be great!
You're confusing your Customer class with its name property. You can't check if a list of Custom contains a String because it never will. But you can check if any customers in the list have the property you're looking for. If you don't find any, then you have to construct a new object with that string:
public void addCustomer(String name) {
for (Customer c : customerList) {
if (c.getName().equals(name)) {
// duplicate found
return;
}
}
// no duplicates; add new customer
customerList.add(new Customer(name));
}
This assumes Customer has a constructor Customer(String name) and a method String getName(). Adapt as necessary.
Customer is a class and you made an array list of Customer class type.there is no direct way to compare name(String) with Customer class object.
You should change your code like-
public void addCustomer(String name) {
for (Customer c : customerList) {
if (!c.getName().equals(name)) {
Customer c=new Customer();
c.setName(name);
customerList.add(c);
}
}
}
And in Customer Class
Class Customer{
private String name;
//getter and setter method for name.
}
I'm having problems getting a method from one class to work if I put the objects into a set.
So I have
public class Employee {
/* instance variables */
private String firstName;
private String employeeNumber;
public Employee(String employNum) {
super();
this.employeeNumber = employNum;
}
...
public String getFirstName() {
return this.firstName;
}
There is lots of other code which I can post if needed but I'm not allowed to change the Employee class.
So for my code I have to create a class for a Set of Employees which I've done with
public class Records {
public Set<Employee> employeeSet = new HashSet<Employee>();
public Records() {
}
}
Now I need a method that will print the details of all employees in the set. Here is my attempt so far
public void printEmployeeNames() {
for (String employee : employeeSet) {
System.out.println(this.employeeSet.getFirstName());
}
}
The problem I'm having is that it won't compile as it says
"incompatible types"
and highlights employeeSet in
for (String employee : employeeSet)
My other problem is that it can't access the method for getFirstName(). I've tried to isolate the method using
public void printEmployeeNames() {
System.out.println(this.employeeSet.getFirstName());
}
This also won't compile as it states
"cannot find symbol - method getFirstName()".
Edit.
Thanks for the help with this problem, I changed it to this and it worked.
public void printEmployees()
{
for (Employee employee: employeeSet)
{
System.out.println(employee.getFirstName());
}
}
this here makes no sense:
for (String employee: employeeSet)
{
System.out.println(this.employeeSet.getFirstName());
}
since the employeeSet is a Set and sets dont have a method called getFirstName
you have to do:
for (Employee employee: employeeSet) //for every EMPLOYEE in the employeeSet
{
System.out.println(employee.getFirstName()); //from that employ get the name
}
AND create in the Employee class the respective Setter and getters
in this case:
private String firstName;
/**
* #return the employeeNumber
*/
public final String getEmployeeNumber() {
return firstName;
}
That should be
for (Employee employee: employeeSet)
{
System.out.println(employee.getFirstName());
}
Set doesn't have a firstname method. Your employee object have have.
First of all, have you heard of encapsulation? The declaration public Set<Employee> employeeSet is an example of a bad practice, and you should use a private field with some sort of getter. The reason your for loop is raising errors is that you made two mistakes:
employeeSet is a List<Employee>, whereas you are asking for a String when iterating over it. This is incorrect - change the type of employee to Employee.
You are trying to access getFirstName() from your field employeeSet. This won't work, as Set has no such method. I believe you meant to call the method on employee.
Also, you may simplify your code to the following one-liner with Java 8 streams:
public void printEmployeeNames() {
employeeSet.stream().map(Employee::getFirstName).forEach(System.out::println);
}
I need to print the first name, last name, and salary from two employee objects but I keep getting a cannot find symbol error. What would I do to fix this?
Here is the constructor class:
public class Employee
{
private String firstName;
private String lastName;
private double monthlySalary;
public Employee( String firstName1, String lastName1, double monthlySalary1) {
setfirstName(firstName1);
setlastName(lastName1);
setmonthlySalary(monthlySalary1);
}
String getfirstName() {
return firstName;
}
String getlastName() {
return lastName;
}
double getmonthlySalary() {
return monthlySalary;
}
public void setfirstName (String firstName1) {
firstName = firstName1;
}
public void setlastName (String lastName1) {
lastName = lastName1;
}
public void setmonthlySalary (double monthlySalary1) {
monthlySalary = ( monthlySalary1 >= 0 ? monthlySalary1 : 0);
}
}
And here is what I have so far to print the objects:
public class EmployeeTest {
public static void main(String[] args) {
Employee a = new Employee("John", "Smith", 10000);
Employee b = new Employee("Jane", "Smith", 11000);
System.out.print(a.firstName1);
}
}
I need to be able to have it print out something along the lines of "Name: Salary:" But I am clueless as to how to make this work. Any help would be greatly appreciated.
In your employee class, you need to override the toString() method.
You can try something like:
#Override
public String toString()
{
System.out.println("Name: "+name+"Salary: "+salary);
}
Then for each of your employees, when you want to print them, just call
System.out.println(employee);
You cant print out firstName (or firstName1, because that doesnt exist in your class), because its marked as private. You should do something like this:
System.out.print(a.getfirstName())
firstName is private, which means that it cannot be seen outside of the object/class it resides in. I suggest you try overriding the toString() method on your Employee class. That method would have access to all the private members of Employee.
Alternately, you could use getfirstName() to return the first name.
Also, this may be a typo, but there is no firstName1 in Employee - it is firstName.
I need for Search method for a hashmap and I cant quite figure out how to do it. I'm also trying to do a edit method and I think for this I need the method. My hashMap is to store employee data. I have the MainApp, Employee class and an EmployeeStore class. Can anyone help?
public class MainApp
{
public static void main(String[] args)
{
new MainApp().start();
}
public void start()
{
EmployeeStore Store = new EmployeeStore();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));
Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
Store.print();
Store.clear();
Store.print();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));
Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
Store.print();
Store.remove("Andy Carroll");
Store.print();
}
}
//Imports.
import java.util.HashMap;
//********************************************************************
import java.util.Map;
public class EmployeeStore
{
HashMap<String, Employee> map;
//Constructor.
public EmployeeStore()
{
map = new HashMap<String,Employee>();
}
//********************************************************************
//Hashmap Methods.
//Add to the Hashmap : Employee.
public void add(Employee obj)
{
map.put(obj.getEmployeeName(), obj);
}
//********************************************************************
//Remove from the Hashmap : Employee.
public void remove(String key)
{
//Remove the Employee by name.
map.remove(key);
}
//********************************************************************
//Clear the Hashmap : Employee.
public void clear()
{
map.clear();
}
//********************************************************************
//Print the Hashmap : Employee.
public void print()
{
System.out.println("\n********Employee's in the Company.********");
for (Employee employee : map.values())
{
System.out.println("Employee Name:\t" + employee.getEmployeeName());
System.out.println("Employee Id:\t" + employee.getEmployeeId());
System.out.println("E-mail:\t"+ employee.getEmployeeEmail());
}
}
//********************************************************************
//********************************************************************
}
//Imports:
//********************************************************************
//Employee Class.
public class Employee
{
//Variables.
private String employeeName;
private int employeeId;
private String employeeEmail;
//********************************************************************
//Constructor.
public Employee(String employeeName, int employeeId, String employeeEmail)
{
this.employeeName = employeeName;
this.employeeId = employeeId;
this.employeeEmail = employeeEmail;
}
//********************************************************************
//Getters.
public String getEmployeeEmail() {
return employeeEmail;
}
public void setEmployeeEmail(String employeeEmail) {
this.employeeEmail = employeeEmail;
}
public String getEmployeeName() {
return employeeName;
}
public int getEmployeeId() {
return employeeId;
}
//********************************************************************
//toString method.
public String toString() {
return "Employee [employeeName=" + employeeName + ", employeeId="
+ employeeId + ", employeeEmail=" + employeeEmail + "]";
}
//********************************************************************
}
Since this is homework I'll only guide you.
You have two options:
First of them is to create additional maps, mapping id-Employee and email-Employee, then fill all three maps when adding new employee. Getting employee would require to use Map.get(key) method on one of those maps.
Second, seems like better suiting your need, option is to retrieve all values from map - using Map.values(), iterate over them (using foreach), and check if id or email of given employee is the one that you was looking for - using object.equals(object2) method.
and one last thing - try to write clean code, so be precise in naming - in place of:
public void add(Employee obj)
{
map.put(obj.getEmployeeName(), obj);
}
try following:
public void add(Employee employee)
{
map.put(employee.getEmployeeName(), employee);
}
It does make the difference, trust me :)
EDIT:
Going back to naming advice - When you have class Named Employee its redundant to name method with word Employee within - as you did with employee.getEmployeeName().
It's quite obvious, that you want to get name of empoyee, not his dog, nor couch :) employee.getName() (that gets value of field named name - not myName or employeeName) is simpliest and best idea that you shoud have :)