Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

using arrays and classes in java

Options
  • 06-12-2013 9:22pm
    #1
    Registered Users Posts: 2,799 ✭✭✭


    hi guys just a quick question cause i'm a bit stumped learning java!

    If i have a class say Employee and its attributes are name,salary etc includes all my Constructors, getter an setter methods and a toString to print the object.

    I have to create an array of Employee(I called it EmployeeArr) in another class, and then run it from my EmployeeTest class which has my main method.

    In my the EmployeeArr class do i initialise my array as a constructor or can i create it as an attribute and use getter and setter methods.

    can i use my Employee class setters and getters in EmployeeArr class?

    I'm completly stumped about how to create the array in one class and then use it in another in my main method.

    sorry if its a bit of a silly question i'm only starting to learn objects now, and if it seems like a funny way about going about this could you tell me why.

    thanks


Comments

  • Registered Users Posts: 2,024 ✭✭✭Colonel Panic


    Post some code. If you write a class that has an array of Employees, you can give that class a getter that returns the array.
    public Employee[] getEmployees() { /* return your array */ }
    

    Regarding the array itself. Initialise it with the number of Employees you want it to hold, then create a loop that adds Employees to it.


  • Registered Users Posts: 29 B000


    mightyreds wrote: »
    In my the EmployeeArr class do i initialise my array as a constructor or can i create it as an attribute and use getter and setter methods.

    You can do both - initialise in constructor and also create getter and setter.


  • Registered Users Posts: 2,799 ✭✭✭mightyreds


    .


  • Registered Users Posts: 2,799 ✭✭✭mightyreds


    My code is just basic now say

    Employee class:
    Attributes:
    name
    Address
    Salary

    Methods:
    getName
    setName
    getAddress
    setAddress
    getSalary
    setSalary
    toString

    All work can access them all from my main method EmployeeTest, can create an array of Employee objects in my main, but I need to create one in a separate class and I don't even know where to begin to do it. I'm not sure how to initialise the array in the class then access it from the main. I'll get up some code but its only really the Employee class and EmployeeTest which creats a few Employee objects I can't figure the array in a separate class at all


  • Registered Users Posts: 29 B000


    Not exactly sure what you want to achieve, but here's some example of how it can be done.
    class EmployeeArr{
        
       // Variables.
       int arraySize = 10;
       Employee[] employees = new Employee[arraySize];
       
       // Constructor.
       EmployeeArr(){
           for( int i=0; i<arraySize; i++ ){
               employees[i] = new Employee();
           }
       }
       
       // Getter.
       Employee[] getEmployees(){
           return employees;
       }
       
        // Setter.
        void setEmployees( Employee[] employees ){
            this.employees = employees;
        }
    }
    


  • Advertisement
  • Registered Users Posts: 2,799 ✭✭✭mightyreds


    Thanks thats great I have a start on that now I can work with that now see can I get it all working and i'll post let you know how I get on.


  • Registered Users Posts: 29 B000


    OK, no problem :)


  • Registered Users Posts: 2,799 ✭✭✭mightyreds


    That helped a great amount just stuck on 1 last bit hers my code
    public class Employee {
            // attributes
    	private int number;
    	private String name;
    	private String address;
    	private String department;
    	private double salary;
    	private String reg;
    	
    	public Employee(){
    		setNumber(0);
    		setName("");
    		setAddress("");
    		setDept("");
    		setSalary(0);
    		setReg("");	     //constructor for 0 attributes
    	}
    	public Employee(int number,String name,String address){
    		setNumber(number);
    		setName(name);
    		setAddress(address);
    		setDept("");
    		setSalary(0);
    		setReg("");	      //constructor for 3 attributes
    	}
    	public Employee(int number,String name,String address,String dept,int salary,String reg){
    		setNumber(number);
    		setName(name);
    		setAddress(address);
    		setDept(dept);
    		setSalary(salary);
    		setReg(reg);	//constructor for all attributes
    	}
    	
    	
    	public void setNumber(int number){
    		this.number=number;	
    	}
    	public void setName(String name){
    		this.name=name;
    	}
    	public void setAddress(String address){
    		this.address=address;	
    	}
    	public void setDept(String department){
    		this.department=department;	
    	}
    	public void setSalary(double salary){
    		this.salary=salary;
    	}
    	public void setReg(String reg){
    		this.reg=reg;	
    	}
    	public int getNumber(){
    		return number;
    	}
    	public String getName(){
    		return name;
    	}
    	public String getAddress(){
    		return address;
    	}
    	public String getDept(){
    		return department;
    	}
    	public double getSalary(){
    		return salary;
    	}
    	public String getReg(){
    		return reg;
    	}
    	public void getInfo(){
    		System.out.println("Employee number: "+number+"\nEmployee name: "+name+"\nEmployee address: "+address+"\nEmployee Salary: "
    				+salary+"\nEmployee Department: "+department+"\nEmployee Regidtration: "+reg);          //this is to print the Employee object
    	}
    	public void taxPayable(){
    		if(salary<=20000){
    			System.out.println("Tax Payable by emoployee "+number +" is "+salary*.20);
    		}else{
    			System.out.println("Tax Payable by emoployee "+number +" is "+salary*.40);
                           //calculates the tax payable by Employee and prints it
    		}
    		
    	}
    	
    }
    

    class EmployeeArray{
        
       // Variables.
       int arraySize = 10;
       Employee[] employees = new Employee[arraySize];
       
       // Constructor.
       EmployeeArray(int number,String name,String address){
           for( int i=0; i<arraySize; i++ ){
               employees[i] = new Employee(number,name,address);
                //for 3 attributes of Employee
           }
       }
       EmployeeArray(int number,String name,String address,String dept,int salary,String reg){
           for( int i=0; i<arraySize; i++ ){
               employees[i] = new Employee(number,name,address,dept,salary,reg);
               //constructor with all attributes added
           }
       }
       
       // Getter.
       Employee[] getEmployees(){
           return employees;
       }
       
        // Setter.
        void setEmployees( Employee[] employees ){
            this.employees = employees;
        }
        public void printArray(){
        	for( int i=0; i<arraySize; i++ ){
                employees[i].getInfo();
        	System.out.println();
        	}
        }
    }
    


    public class EmployeeDriver {
    
    	public static void main(String[] args) {
    		Employee emp1=new Employee(110,"Dan","Kildare","store",25000,"99-d-604");
    	
    		EmployeeArray shop=new EmployeeArray(221,"Dan","Kildare","Warehouse",25000,"131-d-9484756");
    	
    	
    		shop.printArray();
    		
    				
    				
    				
    	}
    
    }
    


    Now can i access each element of the array so when i'm creating the array i have 10 different employees?
    would i have to create a constructor that takes a number for the array index and the values for my Employee Attributes?
    when i create the array it has all the same data for each employee.
    maybe if i want to print one member would my print statement take in an index to print that employees information?


  • Registered Users Posts: 29 B000


    In that case, unless you have employees' info stored somewhere, you have to populate that array manually, without the for loop.
    // Constructor.
       EmployeeArray(){
           
           employees[0] = new Employee( 1, "someName1", "someAddress1" );
           employees[1] = new Employee( 2, "someName2", "someAddress2" );
           employees[2] = new Employee( 3, "someName3", "someAddress3" );
           // etc.
       }
    


  • Moderators, Technology & Internet Moderators Posts: 1,335 Mod ✭✭✭✭croo


    Now can i access each element of the array so when i'm creating the array i have 10 different employees?
    your EmployeeArray class might need a method to add an element that is an instance of your Employee class? ;)
    but you'd have to ask yourself, do you want an Array or a List and if it's just an Array then why not take the easy route and use a simple array on its own?
    Employee[] employees = new Employee[10]
    

    You could move the printArray to the driverclass.

    If you wanted to go the route of the EmployeeArray acting as a list then you could have some additional methods like methods to; addEmployee, deleteEmployee & perhaps updateEmployee.
    when i create the array it has all the same data for each employee.
    Look closely at your EmployeeArray constructor.
    EmployeeArray(int number,String name,String address,String dept,int salary,String reg){
           for( int i=0; i<arraySize; i++ ){
               employees[i] = new Employee(number,name,address,dept,salary,reg);
               //constructor with all attributes added
           }
       }
    
    Each time you create a new instance of EmployeeArray, you loop for arraySize times (10) and fill all the elements of the array with the new Employees created with the details of the ONE employee you passed in.
    The only method you have to add employees is via the constructor which means the EmployeeArray will always be 10 elements of the same employee details (each a different instance of the Employee Class though!!).


  • Advertisement
  • Registered Users Posts: 2,021 ✭✭✭ChRoMe


    Do your self a favor and use a collection like ArrayList.


  • Moderators, Technology & Internet Moderators Posts: 1,335 Mod ✭✭✭✭croo


    ChRoMe wrote: »
    Do your self a favor and use a collection like ArrayList.
    In the real world that's how you go but if someone is learning, as the OP obviously is here, then they might be being asked to push the limits of a concept (an array in this case) as a way of ensuring they understand it fully.

    It really depends on what their teacher's goal is of the excerise and what constraints they placed on the exercise!? It seems to be if the OP just uses a standard collection class then they will move on without ever understanding the array and what the collection is really doing for them. I would thing understanding these basic data structures (starting with arrays and moving on to lists, sets, queues, stacks, etc) is pretty fundamemtal.


  • Registered Users Posts: 27,163 ✭✭✭✭GreeBo


    +1

    in reality you'd use a list for this, but that doesn't help you learn about arrays.
    however, the example is a little unrealistic and convoluted.
    You need to jump through hoops now, all because your array is encapsulated/hidden in your employeearr class.

    unless it's a requirement I'd ditch that extra class and use the array in your driver/main class as croo advised.

    if not, then you need to provide a way of adding to your array from outside the class, using a circular array would help avoid having to grow the array, but again, depends on requirements.


  • Registered Users Posts: 2,799 ✭✭✭mightyreds


    yeah i wont be back now till Wednesday so i'll ask about the extra class, i think it must be a mistake in the question, for now i put in a addEmployee method. I just let the constructor create the array and then fill it manually in my driver but to me it seems like a long way round just straight up creating the array in the driver.
    shop.addEmployee(0, 223,"john", "Kildare", "store",34000,"131-d-34564");
    		shop.addEmployee(1,224,"Joe","Carlow","Store",28000,"04-cw-2345672");
    		shop.addEmployee(2,110,"Dan","Kildare","store",25000,"87-d-64546");
    


    I looked at Arraylist breifly i think i'll read into that a bit more now and try it that way too at the very least i'll get an insight into lists anyway.


  • Registered Users Posts: 27,163 ✭✭✭✭GreeBo


    to learn a bit more about arrays, create one of size 5, and then call addEmployee 6 times...
    also play with deleting and adding things in it, for example think about implementing a queue with an array...the implications of this.

    things like this will help you figure out when you want an array instead of a list, and when you don't


  • Registered Users Posts: 2,799 ✭✭✭mightyreds


    Thanks guys it took a bit of work but I think I have the deleteEmployee and addEmployee working now just to think about the edit part hers my 2 bits of code
    public void addEmployee(int number,String name,String address,String dept,int salary,String reg){
            this.employees= Arrays.copyOf(employees,employees.length + 1);
            employees[employees.length - 1] = new Employee(number,name,address,dept,salary,reg);
            
            //this is a method to add an employee to the array it copies the original array and adds an element to it
        }
    

    deleteEmployee
    public void deleteEmployee(int index){
        	Employee[] n=new Employee[employees.length-1];
        	
        	for (int i=0; i < employees.length; i++) {  
        		  if (i == index) {  
        		      employees[i] = null; 
        		  } else {  
        		      n[i] = employees[i];
        		  }   
        		}
        	employees=Arrays.copyOf(n,n.length);
        	// delete an employee from an array and shift the elements down one 
        }
    

    I had a much easier time of the add employee because of the arrayCopy but i couldn't get anything like it for deleting.
    I seen a few copyRange methods but I couldn't get it working properly, I knew that I could create an array copy like above, copy into it the range 0 to index then copy index to array.length, then call this at the end employees=Arrays.copyOf(n,n.length); but I just couldn't get it going so ended up with my longer code above.

    I think I'm gone way off the track for what the question was(I wont know till to morrow) but I reckon I know a bit more about objects and arrays then when i started.


Advertisement