I'm new to JAVA and I struggled with this question which is very unclear to me. I'm politely asking if someone could discussing it with me or teach me how to answer it? Thank you.
Question:
A Company class holds an array of employees and its constructor takes in as parameters 4 arrays of the same length. The first array is an array of String being the names of employees; the second array is an array of String being the respective addresses; the third array is an array of int being the respective employee numbers; the fourth array is an array of double being the respective salaries.
I know how to do the public constructor one but I am unsure about the constructor of the class Company.
Your help is very valuable to me. Thank you in advance.
Feels like a very simple class structure.
public class Company {
Employee[] employees;
public Company (String[] names, String[] addresses, int[] ids, double[] salaries) {
employees = new Employee[names.length];
for (int i = 0; i < employee.length; i++) {
employees[i] = new Employee (names[i], addresses[i], ids[i], salaries[i]);
}
}
static class Employee {
String name;
String address;
int id;
double salary;
Employee (String name, String address, int id, double salary) {
this.name = name;
this.address = address;
this.id = id;
this.salary = salary;
}
}
}
Please delete question if this is a school assignment and you are using stackoverflow to cheat.
public Company(String[] names, String[] addresses, int[] employeeNumbers, double[] salaries) {
}
A better design would be
public Company(Employee[] employees) {
}
and have an employee class
public class Employee {
private String name;
private String address;
private int employeeNumber;
private double salary; // you may not want to use this in production
public Employee(String name, String address, int employeeNumber, double salary) {
}
// constructors, getters and setters, etc
}
According to #Kayaman comment seems you already have an employee class but for some reason you don't want to use the first constructor that takes an array of employees instead of 4 arrays. You want to use the first constructor with the 4 array parameters and construct array objects from the parameters. That's actually bad programming. It makes you code look dirty.
If it's a school assignment and you are required to do it that way, I'm guessing the instructor probably just wants you to learn something out of it. But code like that should not be written in production.
Anyways, here is the solution you might be looking for
public class Company {
private Employee[] employees;
public Company(String[] names, String[] addresses, int[] employeeNumbers, double[] salaries) {
employees = new Employees[names.length]; // assuming all arrays are of the same length
for (int i = 0;i < employees.length;i++) {
employees[i] = new Employee(names[i], addresses[i], employeeNumbers[i], salaries[i]);
}
}
}
import java.util.ArrayList;
import java.util.Collections;
public Class Company
{
ArrayList<Employee> employees = new ArrayList<Employee>();
public Company(Employee[] newEmployees)
{
employees.addAll(newEmployees);
}
}
public Class Employee
{
public String Name;
public String Address;
public Int Id;
public Double Salary;
public Employee(string name, string address, int id, double salary)
{
this.Name = name;
this.Address = address;
this.Salary = salary;
this.Id = id;
}
}
To create a new company:
Employee[] e = {
new Employee("Bob", "Bobs address", 1, 50000),
new Employee("Jane", "Janes address", 3, 85000)
}
Company c = new Company(e);
Related
I have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();
I need to create an object array and read the values of the elements in the constructor from console. I am totally confused how to do it.Can anyone give a clarity about how to do it
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
id = this.id;
name = this.name;
marks = this.marks;
}
}
public class Solution {
public static void main(String[],args)
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
Student[] arr=new Student[n];
for(int i=0;i<n;i++)
{
int x =sc.nextInt();
String y=sc.nextLine();
double z=sc.nextDouble();
arr[i]=arr.Student(x,y,z);
}
}
}
I am confused on how to call the constructor.
Can anyone help me?
You can do one of two things:
1.Create a temporary object by calling the constructor and then adding that object in the array:
Student temp= new Student(x,y,z);
arr[i]=temp;
2.Directly instantiate a new object and add it in the array like this:
arr[i]=new Student(x,y,z);
Both methods will work fine, but it is recommended to use method 2 because you should not allocate memory to a temp object when clearly you can achieve the goals without doing so
Instead of:
arr[i]=arr.Student(x,y,z);
Do:
arr[i]=new Student(x,y,z);
Why? Because, Each object in the array is an instance of Student class
Your constructor is declared wrongly. this is always used to refer to the instance variable. Change your constructor to this:
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
} }
public class Solution {
public static void main(String[],args)
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
Student[] arr=new Student[n];
for(int i=0;i<n;i++)
{
int x =sc.nextInt();
String y=sc.nextLine();
double z=sc.nextDouble();
arr[i]= new Student(x,y,z); //no need to create an object for arr
}
}
}
Because your constructor is wrong.
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
}
I have a project where I want to store data about students(name,age,registration number etc)
I don't know how else to store the data so I thought arrays would be worthwhile. How would I link data from the name array to the age array????
In first, create a Student object like this:
public class Student {
private final String name;
private final int age;
private final int registrationNumber;
public Student(String name, int age, int registrationNumber) {
this.name = name;
this.age = age;
this.registrationNumber = registrationNumber;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getRegistrationNumber() {
return registrationNumber;
}
}
And after, you can create a list of Student who provide an in memory storage for your students:
List<Student> students = new ArrayList<>();
students.add(new Student("Valentin", 23, 123456));
students.add(new Student("Alexander", 14, 82835));
I hope this gonna help you.
I just have this basic code where I need help adding employee data to an ArrayList of another class. I am just writing this code in preparation for an assignment, so don't bash my code too much. Essentially though, i'll be needing to add elements of employees and delete them eventually. But for now, I just need help adding the elements to my other Employee class. =]
public class main {
private static Employee employee;
public static void main(String[] args) {
employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
...............
import java.util.ArrayList;
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> Employee = new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
}
Simple Example -
package com;
import java.util.ArrayList;
public class TestPage{
public static void main(String[] args){
Employee emp1, emp2;
emp1 = new Employee();
emp2 = new Employee();
emp1.setName("MAK");
emp2.setName("MICHELE");
emp1.setAddress("NY");
emp2.setAddress("WY");
//and keep putting other information like this
ArrayList<Employee> employee = new ArrayList<Employee>();
employee.add(emp1);
employee.add(emp2);
System.out.println("emp1 name is : " + employee.get(0).getName());
System.out.println("emp2 name is : " + employee.get(1).getName());
System.out.println("emp1 address is : " + employee.get(0).getAddress());
System.out.println("emp2 address is : " + employee.get(1).getAddress());
}
}
class Employee{
String name, address;
int age, salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
It seems like what you're asking is based on one employee having sub-employees and that structurally that probably represents a hierarchy (Some commenters seem to be missing that point). But that's an assumption on my part. Based on that assumption.
A little bit of feedback to start on structure of your main class:
public class main {
public static void main(String[] args) {
Employee employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
It seems to me that there's no reason to have a static instance variable for that root employee instance. You should try to limit the scope of variables where possible. It seems like it could very well be in the main() method's scope.
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> employees= new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
public ArrayList<Employee> getEmployees() {
return this.employees;
}
}
It may be better to name your arraylist employees or employeeList. I went with employees in this case because that convention is preferable.
And in relation to your question, ArrayList is pass by reference so you could just add a getter method for the sub-employee list (employees).
To add employees from your main method you could do something like
Employee rootEmployee = new Employee(5, 10.0);
rootEmployee.getEmployees().add(new Employee(6, 5.0));
Or you could add an additional method to Employee like this:
public void addEmployee(Employee e) {
employees.add(e);
}
I've created class Person, which is extended by classes Student and Employee (which is extended by other Employee type classes). The person class looks like:
String name;
int ssn;
int age;
String gender;
String address;
String PNumber;
static int count;
//empty constructor
public Person(){
count++;
}
//print count
public static void printCount(){
System.out.println("The number of people is: "+ count);
}
//constructor with name
public Person(String name){
this.name = name;
count++;
}
/*constructor to create default person object*/
public Person(String name, int ssn, int age, String gender, String address, String PNumber)
{
this.name = name;
this.ssn = ssn;
this.age = age;
this.gender = gender;
this.address = address;
this.PNumber = PNumber;
count++;
}
I'm currently trying to create a method that will display all Persons if they're gender = "Male". I have:
//display Males
public void print(String gender){
if(this.gender.contentEquals(gender)){
//print out person objects that meet this if statement
}
}
I'm not sure how to refer to the objects (students and employees that are all persons) within the method to return them. And I also don't know how to refer to this method in the main method. I can't use Person.print, but if I use
Person james = new Person();
and then use
james.print("Males");
I'm only returning james (and the method doesn't make sense in that context).
Any help appreciated.
First, the print method should be made into a static method. It is independent of each individual Person object, so making it static will allow you to call it in the main method as
Person.print("Male");
To refer to Person objects in the print method, you will need to pass it a collection of Person objects as a parameter. You should keep all instances of Person in an array and pass that into the print method when you call it. Then the print method can be
public static void print(String gender, Person[] people) {
for(Person x : people)
if (x.gender.equals(gender))
//print the person
}
With this modification you should call it from the main method as
Person.print("Male", people);
where people is the array you keep all Person objects in.