Java math operations on variable number of arguments - java

I'm new at starting object oriented programming. I have tried to find a topic that would answer my questions, but I haven't seem to find my answers yet. I hope I'll get help ^^
I am trying to understand something. I have the following class:
class Employee {
private String SIN ; // format "123 456 789", ex : "250 343 567"
private double salWeek ; // example 1075.25 $
. . . Constructors to write . . .
. . . Other methods to write . . .} // End of Employee class
I have to create the following constructors:
Employee emp1 = new Employee("321 498 726", 987.50); // 987.50$ is Total salary for week
Employee emp2 = new Employee("135 444 321", 45.00, 20.00); /* 45 hr x 20$/hr.
900.00 $ is Total salary for week*\
And I have to print informations on the second employee with the following method:
emp2.print("Informations of second employee");
to get
SIN: 135 444 321
Weekly Salary: 900.00$ per week
I am a bit confused since I have two entering arguments for the salary (45 and 20) on which I was thinking doing a math operation (45*20). I just don't seem to understand how to do it.
I then have to modify and print emp1 salary using emp2 salary and adding 123.25$ (giving a total of 1023.25$).
Is it possible to let me know how I could do it? I have code parts if needed.
Thank you!
Here is the code I have so far:
public class Employee {
private String SIN ;
private double salWeek;
public String getNAS() {
return NAS;
}
public double getsalWeek() { //Needs work since emp2 has 2 arguments
/*I was thinking here of adding math operation to get second and third argument and make multiplication if salary has 2 arguments*/
return salWeek;
}
public static void main(String[] args) {
Employee emp1 = new Employee("321 498 726", 987.50);
Employee emp2 = new Employee("135 444 321", 45.00, 20.00); //Weekly salary is 45 * 20
emp2.display("Informations on second employee");
System.out.printf("NAS: %s\n",emp2.getNAS());
System.out.printf("Weekly salary: %d\n",emp2.getsalWeek());
}
}
Edit: Clarification on variables + code part. Code part is NOT complete and needs work.

You can do it as follows:
printInfo(Employee e){
System.out.println("SIN : " + e.getSIN());
System.out.println("Weekly Salary : " + e.getSalHabdo()*e.getSecondSal());
}
Please note that the above method assumes that you have three fields in your class - SIN, salHebdo and the third one which you're setting in the second constructor.
edit-1 : Please provide the getter and setter code of your class and clarification on the third field you're setting using the constructor.

Related

How does 'Stock stock = new Stock("HR.S")' lead to an output?

I'm extremely new to Java, and I'm trying to understand why an output of the main method of the Magic class for this code is "TT". Our professor said we don't have to understand the meaning of this method, but just answer the output.
The code is this.
public class Magic
{
public static void main(String[] args)
{
final String MSG = "Good Restaurant Seattle";
Stock stock = new Stock("HR.S");
double price = stock.getPrice();
int cent = (int) Math.rint(price);
System.out.println(MSG.substring(cent, cent+2).toUpperCase());
}
}
I understand where it took the letters from and how all variables such as cent and price are connected, but I don't understand what "HR.S" is and how it's connected to the output.
In order for MSG.substring(cent, cent+2).toUpperCase() to return TT, the value of cent has to be 20.
....:....1....:....2...
Good Restaurant Seattle
^^
In order for cent to be 20, the value of price must be 19.5 <= price <= 20.5.
Which means that stock.getPrice() returned a value between 19.5 and 20.5 (inclusive).
Not knowing what class Stock does, we cannot say how it figured out that input "HR.S" should have such a price.

Java program not using new value after a change from a mutator

I must have 2 classes and I have to do it based off of my professor's "skeletal" version of testPayroll. I have used as many of the ideas that were given to me already. I need to use the mutator to increase the hours by 10. I then have to recalculate that employee's salary (rate * hours). Finally have have to add the new salary of e1 to the salary of e2.
It appears that I now have the adding part right, but now it seems that the new salary for e1 is just using the salary for e2. I have a feeling this is something really simple. I have been working on this and researching since 6AM this morning :(
Here is the first Class: Payroll
public class Payroll {
static double salary;
static double payout;
private String employee_number;
private int hours;
private double hourly_rate;
public Payroll(String num, int hrs, double rate){
this.employee_number = num;
this.hours= hrs;
this.hourly_rate = rate;
salary = hrs*rate;
payout = salary + salary;
}
public String getNum() {return employee_number;}
public double getHrs() {return hours;}
public double getRate(){return hourly_rate;}
public static double getTotalPayout() {return payout;}
public static double getSalary() {return salary;}
public void increaseHrs(int amount) {hours+=amount;}
}
Here is the TestPayroll:
import java.util.Date;
import java.text.DateFormat;
import java.text.NumberFormat;
class TestPayroll {
public static void main(String[]args){
Date d = new Date();
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Payroll For Week Ending "+df.format(d));
System.out.println("------------------------------------");
Payroll e1 = new Payroll("444-4444",30,25);
e1.getSalary();
displaySalary(e1,nf);
System.out.println("Employee # ...... "+e1.getNum());
System.out.println("Hours worked .... "+e1.getHrs()+" hours");
System.out.println("Hourly rate ..... "+e1.getRate()+"/hour");
System.out.println("Your salary is .. "+nf.format(e1.getSalary()));
System.out.println("------------------------------------\n");
Payroll e2 = new Payroll("555-5555",20,25);
e2.getSalary();
displaySalary(e2,nf);
System.out.println("Employee # ...... "+e2.getNum());
System.out.println("Hours worked .... "+e2.getHrs()+" hours");
System.out.println("Hourly rate ..... "+e2.getRate()+"/hour");
System.out.println("Your salary is .. "+nf.format(e2.getSalary()));
System.out.println("------------------------------------");
e1.increaseHrs(10);
e1.getSalary();
displaySalary(e1,nf);
System.out.println("Increase "+e1.getNum()+ " by 10 hours");
System.out.println("Employee # ...... "+e1.getNum());
System.out.println("Hours worked .... "+e1.getHrs()+" hours");
System.out.println("Hourly rate ..... "+e1.getRate()+"/hour");
System.out.println("Your salary is .. "+nf.format(e1.getSalary()));
System.out.println("------------------------------------\n");
System.out.println("Total payout amount ..
"+nf.format(Payroll.getTotalPayout()));
System.out.println("------------End of Report-----------\n");
}
public static void displaySalary(Payroll e,NumberFormat nf){
}
}
Here is the program run:
Payroll For Week Ending May 16, 2018
------------------------------------
Employee # ...... 444-4444
Hours worked .... 30.0 hours
Hourly rate ..... 25.0/hour
Your salary is .. $750.00
------------------------------------
Employee # ...... 555-5555
Hours worked .... 20.0 hours
Hourly rate ..... 25.0/hour
Your salary is .. $500.00
------------------------------------
Increase 444-4444 by 10 hours
Employee # ...... 444-4444
Hours worked .... 40.0 hours
Hourly rate ..... 25.0/hour
Your salary is .. $500.00
------------------------------------
Total payout amount .. $1,000.00
------------End of Report-----------
Your problem is in the semantics of your class structure, and you are using static and instance variables alternatively. You create an instance of PayRoll for each employee, which is having instance attributes like hourlyRate, salary, hours and all. And you are tracking the total payout as a static variable totalPayout.
When you do this, you need to properly refer to the variables, using this keyword. And there was a semantic error in your implementation, which is, every time you increase the hours, you need to add the total for that increment to the total payment, which you have not done. So, what you need to do is something like follows. I have taken the liberty of minifying your example for the sake of simplicity. I hope this will be an example for you to understand what a minimal, complete and verifiable example is.
class PayRoll{
private static double totalPayout;
public static double salary;
private int hours;
private double rate;
public PayRoll(int hrs, double rate){
this.rate = rate; // Note the usage of this keyword
this.hours = hrs;
totalPayout += (hrs * rate);
}
public void increaseHrs(int amount){
hours += amount;
totalPayout += (this.rate * amount); // This was not there in yours. also note the use of `this` keyword.
}
public static double getTotalPayout(){
return totalPayout;
}
}
class PayRollRun{
public static void main(String args[]){
PayRoll e1 = new PayRoll(30, 25);
PayRoll e2 = new PayRoll(40, 25);
System.out.println(PayRoll.getTotalPayout());
e1.increaseHrs(10);
System.out.println(PayRoll.getTotalPayout());
}
}
However, I see a lot of flaws in your way of doing this. What I think you should do is, have a List of Employees in the PayRoll class. So, you will write an employee class separately from PayRoll and have a List of Employee instances in PayRoll class.
As a simple answer, to your specific question:
it seems that the new salary for e1 is just using the salary for e2
this is because you have the salary in Payroll as static, i.e. your line:
static double salary;
would be better written as:
private double salary;
By making it static, you are sharing the value of salary across all instances of Payroll - so when you first create e1, you set the value to 30 * 25, then, when you create e2 you set the value to 20 * 25. Because salary is static, there is only one copy of this value shared by both e1 and e2, so the second time you set it, you update both e1 and e2's salaries to the new value.
Romeo Sierra's answer is much more complete, and a better answer than this one, so you should consider all the points from that answer along with this, but this should resolve the specific issue you have asked about.

Creating and accessing Array data in Java

I have a a textbook question that I have attempted many times and still does not work here are the instructions:"
Write a Payroll class that uses the following arrays as fields:
employeeId. An array of seven integers to hold employee identification numbers. The array should be initialized with the following numbers:
5658845 4520125 7895122 8777541 8451277 1302850 7580489
hours . An array of seven integers to hold the number of hours worked by each employee
payRate . An array of seven double s to hold each employee’s hourly pay rate
wages . An array of seven double s to hold each employee’s gross wages
The class should relate the data in each array through the subscripts. For example, the number in element 0 of the hours array should be the number of hours worked by the employee whose identification number is stored in element 0 of the employeeId array. That same employee’s pay rate should be stored in element 0 of the payRate array.
In addition to the appropriate accessor and mutator methods, the class should have a method that accepts an employee’s identification number as an argument and returns the gross pay for that employee.
Demonstrate the class in a complete program that displays each employee number and asks the user to enter that employee’s hours and pay rate. It should then display each employee’s identification number and gross wages.
Input Validation: Do not accept negative values for hours or numbers less than 6.00 for pay rate."
so far I have my main class:
public class Payroll {
public static void main(String[] args){
Pay work = new Pay();
Scanner input = new Scanner(System.in);
int[] hours = new hours[work.getLength()];
for (int i=0; i<work.getLength(); ++i) {
System.out.println("How many hours has Employee #"+work.getEmployeeId(i)+" worked?");
input.nextInt() = hours[i];
while (hours[i]<6){
System.out.println("Error, inadequit value!");
System.out.println("How many hours has Employee #"+work.getEmployeeId(i)+" worked?");
input.nextInt() = hours[i];
}
}
}
I also have a class named Pay:
public class Pay {
private int[] employeeId;
//private int[] hours = new hours[employeeId.length];
//private int[] pay = new pay[employeeId.length];
//private int[] wage = new wage[employeeId.length];
public Pay() {
employeeId = new int[]{5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
}
public int getLength(){
return employeeId.length;
}
public int[] getEmployeeId(int id) {
return employeeId[id];
}
I'm just not sur where to go next after all of this. Please help.
I am going to answer this for the simplest way instead of the proper way, since I'm assuming you are somewhat new to programming. This is based on the fact that there seems to be no emphasis on class or any real modularization.
You just want to have 4 arrays of size 7.
The employee ids array will be set by you.
As you prompt the user for the information you save it in the correct array based on the index of the employee being set.
The method for gross pay would just take the id number of the employee, find their index number in the arrays and get the information necessary to calculate and return the gross pay. (presumably gross pay is wageRate * hoursWorked)
This is the simplest way of doing it, separate classes aren't necessary.
A better way of doing this, on object-oriented principles, will be to avoid using multiple arrays. Instead create a class that holds all the employee attributes together, as an object.
public class Employee {
private int id;
private int hours;
private double rate;
// constructors
// it should not have arguments such as id, hours or rate
// because it is a method of this class and those attributes are
// implicitly assumed.
public double getWage() {
return hours * rate;
}
// toString method
#Override
public String toString() {
return "Employee ID = " + id + "," + "hours = " .....
}
}
Wage can be pre-calculated and stored as another field at the time of construction. Or calculated at the time of request as is done above.
The Payroll class:
public class Payroll {
private Employee[] employees;
private int lastIndex = 0;
// constructors
// for example, one constructor can accept initial size
public Payroll(int size) {
employees = new Employee[7];
};
public addEmployee(Employee employee) {
// need to check overflow before attempting to add
// add employee
employees [lastIndex ] = emplyee;
lastIndex++;
}
// more methods, such remove etc
}
Now the driver, or application class
public class Driver {
public static void main(String[] args){
Payroll payroll = new Payroll (7);
// code to pupulate the Payroll with values
for ( ) {
// construct new Emplyee object
// add object to Payroll
}
// Printing
for (Emplyee e: Payroll) {
System.out.println(e.toString());
}
}
}
Note that the application or driver class is separated from the Payroll, now each class does one thing, and only that thing. Remember that it is not the concern of Payroll class to populate itself or print its content etc.

Reading a text file and separating it with delimiter

I am kinda stuck on the following problem and need some guidance. I am trying to read a text file and separate it within a program that I already wrote. The text file will look as follows.
2014 Employee lock,John 3000
2015 Salesman Manning,Bill 4000 50000
2014 Executive Zuck,George 2000 55
I know that I can created a array of objects such as:
Employee[] employee2014 = new Employee[10];
Employee[] employee2015 = new Employee[10];
I am unsure how to use a delimiter to separate the different years and then store the employee information into those years in order. I already wrote three classes for (Employee is parent class to salesman and executive) the program but just need the guidance on the delimiter to store the information in the object. also I don't want to use a array list because my text file only has a limit of 10 items.
Here is an example of one the sub classes Saleman. The parent class Employee and other subclass Executive have the same methods and toString, so I will not post them.
public class Salesman extends Employee {
protected double annualSales;
public Salesman(int monthlySalary, String name, double annualSales)
{
super(monthlySalary, name);
this.annualSales = annualSales;
}
#Override
double annualSalary() {
double commission = .02;
commission = commission * annualSales;
if(commission > 20000)
{
commission = 20000;
}
return (super.annualSalary() + commission);
}
#Override
public String toString() {
return (super.toString() + "\nAnnual Sales: " + annualSales);
}
}
I will be using a filreader and bufferedreader to read the file, but how will I use a delimiter to separate into the class objects to be read by the years?

How do I create a method to calculate a commission fee in Java

I am trying to create a method in Java where a band has a commissioning fee based on the number of artists it has. So it will be 10 pounds for each artist.On the program, when you create the band, you input the artists in the band. The commission fee is then based on the number of artists ( £40 for each artist).
What I currently have is:
private void setCommission()
{
commission = artists+40;
}
Can someone advise on how I can get my method to function correctly or if theres anything else I should add to my current version.
private void setCommission() {
commission = (artists * 40);
}
Your math is messed up. It should be artists * 40 Or, if artists is a list of some sort than you need to multiply its length by 40.

Categories

Resources