I am having difficulty passing the hours and hourlyWage arguments to the constructor in the Paycheck class. The issue is as follows:
symbol: variable hours
location : class Paycheck
It repeats for every instances of hours or hourly wage in public class Paycheck.
The code is as follows
import java.util.Scanner;
public class PayDayCalculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Hourly wage: ");
double hourlyWage = in.nextDouble();
System.out.println("Hours worked: ");
double hours = in.nextDouble();
Paycheck paycheck = new Paycheck(hourlyWage, hours);
System.out.println("Pay: " + paycheck.getPay());
}
}
public class Paycheck {
private double pay = 0;
private double overtime = 0;
private double overtimePay = 0;
/*double hours;
double hourlyWage; */
Paycheck(double hourlyWage, double hours) {
setPay(0);
}
public void setPay(double newPay) {
if (hours > 40) {
overtime = hours % 40;
hours = hours - overtime;
}
overtimePay = hourlyWage * 1.5;
pay = (hours * pay) + (overtime * overtimePay);
}
public double getPay() {
return pay;
}
}
You have commented out member variable hours:
/*double hours;
double hourlyWage; */
but still try to refer to it, e.g.:
if (hours > 40) {
overtime = hours%40;
hours = hours - overtime;
}
If you need this variable - uncomment it.
Your setPay method is referring to hours and hourlyWage, which are parameters passed in to the constructor, making them local only to the constructor. They are not available to all methods in the class. Those need to be uncommented at the class level if you want all methods to have access to them.
double hours;
double hourlyWage;
Paycheck(double hourlyWage, double hours) {
this.hourlyWage = hourlyWage;
this.hours = hours;
setPay(0);
}
hours and hourlyWage are not defined!
Uncomment this part -
/*double hours;
double hourlyWage; */
Related
Please help me with this netbeans assignment code. I have been working on it for a few hours, and I don’t understand it.
Thanks!
I would avoid using raw user input for now, and just focus on creating a reusable method that does your calculation internally. There is no reason to cast to a float, because all the values should be floating-point values.
The calc method handles the calculation that you have copy-pasted three times.
public class CalculateHalfLife {
public static double calc(double amount, double halfLife, double hours) {
return amount / (Math.pow(2, (hours / halfLife)));
}
public static void main(String[] args) {
double amount = 100; // mg of caffeine
double halfLife = 6; // hours
double[] allHours = { 6, 12, 24 };
for (double hours : allHours) {
double output = calc(amount, halfLife, hours);
System.out.printf("After %.0f hours: %.2f mg\n", hours, output);
}
}
}
If you want to to support user input, you should prompt the user to enter input:
import java.util.Scanner;
public class CalculateHalfLife {
private static double amount = 100; // mg of caffeine
private static double halfLife = 6; // hours
private static double[] allHours = { 6, 12, 24 };
public static double calc(double amount, double halfLife, double hours) {
return amount / (Math.pow(2, (hours / halfLife)));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an amount: ");
float amount = sc.nextFloat();
System.out.println();
for (double hours : allHours) {
double output = calc(amount, halfLife, hours);
System.out.printf("After %.0f hours: %.2f mg\n", hours, output);
}
sc.close();
}
}
I'm in my intro to Java class and working on loops this week. I think I have the loop built but my variable within my main CommissionNotifications is undefined.
I think I have to create an object and reference the variable stored in my other class...am I on the right track?
The program asks for annual sales and then calculates there commission payment based upon the bracket they fall into. The commission payment is done through a If statement on the class and then the program displays what they could earn if they increased there sales by 5,000 up to 1.5 * of there sales. IE if they earn 100000 in sales the table should display there initial commission and then what they could earn if they increased there sales to 150000(1.5*)
Here is my class:
public class Calculations {
double TotalSales;
double ComRate = 0.025;
double AnnualSal = 80000;
double compensation;
double SalesTarget;
double Acceleration = 1.5;
double chart;
double ComAccFactor;
public double getCommissionNotifications() {
return CommissionNotifications;
}
public void setCommissionNotifications(double commissionNotifications) {
CommissionNotifications = commissionNotifications;
}
public double CommissionNotifications; {
if (TotalSales > 120000){
CommissionNotifications = AnnualSal + (TotalSales * (ComRate + Acceleration));
} else if (TotalSales > SalesTarget * .8) {
CommissionNotifications = AnnualSal + (TotalSales * ComRate);
} else {;
CommissionNotifications = AnnualSal;
}
}
}
Here is my Main
import java.util.*;
import java.text.*;
public class Paycheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Enter Total Commission Sales: ");
double TotalSales = input.nextDouble();
double Base = TotalSales;
double finish = TotalSales * 1.5;
System.out.println("Your Total compensation with your annual sales is: " + getCommissionNotifications);
int i = Base + 5000;
while (i <= finish) {
System.out.println(Base);
TotalSales += 5000;
}
}
}
getCommisionNotifications is a member of class Calculations. To access it you will need to create a new Calculations object:
Calculations c = new Calculations();
c.getCommisionNotifications();
This code looks a lot like C# with the capitalized variable names. Anyways, your
getCommissionNotifications method should handle the logic of what to return based on TotalSales. It's also not clear why you need a setter method, so I've commented that out.
As for using the below class, you need an instance of the Calculations class
Calculations calc = new Calculations();
double TotalSales = input.nextDouble();
calc.TotalSales = TotalSales;
// double Base = TotalSales; // Duplicate variable not needed
double finish = TotalSales * 1.5;
System.out.println("Your Total compensation with your annual sales is: " + calc.getCommissionNotifications());
public class Calculations {
double TotalSales;
double ComRate = 0.025;
double AnnualSal = 80000;
double compensation;
double SalesTarget;
double Acceleration = 1.5;
double chart;
double ComAccFactor;
public double getCommissionNotifications() {
if (TotalSales > 120000){
return AnnualSal + (TotalSales * (ComRate + Acceleration));
} else if (TotalSales > SalesTarget * .8) {
return AnnualSal + (TotalSales * ComRate);
} else {
return AnnualSal;
}
}
// Not sure why this is needed... You have a dynamic getter method
//public void setCommissionNotifications(double commissionNotifications) {
// CommissionNotifications = commissionNotifications;
//}
}
for the assignment, an employee has a ID number, hourly wage and works a certain # of hours. i need to calculate the gross income from those 2 values and then based of that there is withholding from the pay, in my code i believe all that is there but when i test my program i can only calculate the pay that was earned, the withholding and net pay come as a value of 0. i would appreciate any help on the issue, thank you.
// an employee has an ID, get paid an amout hourly and work an amount of hours
// tax is withheld depending on gross pay
public class Employee
{
//withholding calculation
public Employee(String empId, double hrsWrk, double hrPay)
{
employeeId = empId;
hoursWorked = hrsWrk;
hourlyPay = hrPay;
}
// access methods
public String getEmployeeId()
{
return employeeId;
}
public double getHoursWorked()
{
return hoursWorked;
}
public double getHourlyPay()
{
return hourlyPay;
}
public double getWithholding()
{
return withholding;
}
public double getIncome()
{
double income = hourlyPay * hoursWorked;
return income;
}
public double getNetPay()
{
double netPay = income - withholding;
return netPay;
}
// mutator methods
public void setId(String empId)
{
employeeId = empId;
}
public void setHoursWorked(double hrsWrk)
{
hoursWorked = hrsWrk;
}
public void setHourlyPay(double hrPay)
{
hourlyPay = hrPay;
}
//withholding calculator based on income
public void calcWithholding()
{
if(income <= 0)
{
withholding = 0.0;
}
else if(income >0 && income <= 300.0)
withholding = income*10.0/100;
else if(income >= 300.01 && income <= 400.0)
withholding = income*12/100;
else if(income >= 400.01 && income <= 500.0)
withholding = income*15/10;
else
withholding = income*20/100;
System.out.println("withholding is " + withholding);
}
public void displayWithholding()
{
calcWithholding();
System.out.println("Employee " + employeeId + " your income is " + getIncome() + " per week\n you have to pay " + getWithholding());
System.out.println("Employee " + employeeId + " your net income is " + getNetPay());
}
//instance fields
private String employeeId;
private double hoursWorked;
private double hourlyPay;
private double withholding;
private double income;
private double netPay;
}
here is the test program---------------------------------------------
import javax.swing.JOptionPane;
public class EmployeeTest
{
public static void main(String[] args)
{
String employeeId = JOptionPane.showInputDialog("Please enter your Employee ID");
String input = JOptionPane.showInputDialog("Enter your hourly wage");
double hourlyPay = Double.parseDouble(input);
input = JOptionPane.showInputDialog("How many hours have you worked this week?");
double hoursWorked = Double.parseDouble(input);
Employee richard = new Employee(employeeId, hoursWorked, hourlyPay);
richard.displayWithholding();
System.exit(0);
}
}
You're not calling getIncome until after calcWithHolding so the income variable is always zero during the calculation.
The current approach relies on side-effects from calling some of the accessors, this is generally considered to be a bad approach.
I would suggest one of the following
Ensure calculations done in the constructor (or called...)
Separate your concerns so that there is no confusion between data storage, object construction, data accessors and calculations.
Lazy initialization, so that calculated values are only calculated if they have never been accessed.
So I'm writing a program that is supposed to take a person's wage ($7.25) and add their commission, then spit out the total. I input all the requested info and I get 0.0 for the result, which is obviously wrong. Any help is appreciated, thanks!!
HERE'S WHAT I HAVE IN THE DRIVER CLASS:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double hours, sales, total;
DecimalFormat df = new DecimalFormat("$0.00");
Wages emp1 = new Wages();
System.out.println("Please enter the hours worked: ");
hours = input.nextDouble();
System.out.println("Please the amount of sales: ");
sales = input.nextDouble();
System.out.println("Your total pay check wages are: " + df.format(emp1.getEverything()));
}
AND HERE'S THE WAGES CLASS I CREATED:
public class Wages {
private double PAY_RATE = 7.25;
public double sales, commission, total;
public int hours;
public Wages(){
}
public Wages(double rate,double sales, double total, double commission, int hours){
this.sales = sales;
this.total = total;
this.PAY_RATE = rate;
this.commission = commission;
this.hours = hours;
}
public double getSales(){
return sales;
}
public double getCommission(){
if(sales >= 1.00 && sales <= 99.99){
commission = (sales * 0.05);
return commission;
}
else if(sales >= 100.00 && sales <= 299.99){
commission = (sales * 0.10);
return commission;
}
else if(sales >= 300.00){
commission = (sales * 0.15);
return commission;
}
return commission;
}
public double getEverything(){
total = (PAY_RATE * hours) + commission;
return total;
}
}
You have created a constructor that takes sales and hours, but you didn't use that constructor and instead called default.
So sales and hours have no values.
If I were to do it, I'd change up your Wages class to include this:
public double hours; //You're taking a double for their input, so replace the int
public Wages(double hours, double sales){
this.sales = sales;
this.hours = hours;
}
//...
public double getEverything(){
total = (PAY_RATE * hours) + getCommission();
return total;
}
and use this in the driver:
System.out.println("Please enter the hours worked: ");
hours = input.nextDouble();
System.out.println("Please the amount of sales: ");
sales = input.nextDouble();
Wages emp1 = new Wages(hours, sales);
So i keep getting errors when i try to run the user class saying double is required an no arguments are found. I'm getting errors on lines 17, 40, 42, 44, 46 and 48. They're all errors which say doubles are required. Answers in plain English would be appreciated.
My main class:
import java.util.Scanner;
public class ElectricityCalculatorUser {
//Main method
public static void main (String [] args) {
ElectricityCalculator myCalculator = new ElectricityCalculator();
Scanner input = new Scanner (System.in);
//Input the initial reading
double initialReading;
System.out.print ("What is the inital reading on your electricity meter in kwH? ");
initialReading = input.nextDouble ();
//Input the final reading
double finalReading;
System.out.print ("What is the final reading on your electricity meter in kwH? ");
finalReading = input.nextDouble ();
//Input the number of days
//between readings
double numberOfDays;
System.out.print ("How many days have passed between your initial and final reading? ");
numberOfDays = input.nextDouble ();
//Calculations
double totalElectricityUsed = myCalculator.totalElectricityUsed();
System.out.print ("Total electricity used = " + totalElectricityUsed);
double costOfElectricity = myCalculator.costOfElectricity();
System.out.print ("Cost of electricity = " + costOfElectricity);
double standingCharge = myCalculator.standingCharge();
System.out.print ("Standing charge = " + standingCharge);
double costBeforeVAT = myCalculator.costBeforeVAT();
System.out.print ("Cost before VAT is added = " + costBeforeVAT);
double VAT = myCalculator.VAT();
System.out.print ("Cost of VAT = " + VAT);
double totalCost = myCalculator.totalCost();
System.out.print ("Total cost = " + totalCost);
}
}
My class with all the methods:
public class ElectricityCalculator {
//Attributes
private double initialReading;
private double finalReading;
private double numberOfDays;
//Constructors
public ElectricityCalculator (double ir, double fr, double nod) {
initialReading = ir;
finalReading = fr;
numberOfDays = nod;
}
//Calculating total electricity used
public double totalElectricityUsed () {
return finalReading - initialReading;
}
//Calculating cost of electricity
public double costOfElectricity () {
return totalElectricityUsed * 0.175;
}
//Calculating standing charge
public double standingCharge (double numberOfDays) {
return numberOfDays * 0.25;
}
//Calculating cost before VAT is added
public double costBeforeVAT (double costOfElectricity, double standingCharge) {
return costOfElectricity + standingCharge;
}
//Cost of VAT
public double VAT (double costBeforeVAT) {
return costBeforeVAT * 0.05;
}
//Total cost of electricity used
//including VAT
public double totalCost (double costBeforeVAT, double VAT) {
return costBeforeVAT + VAT;
}
}
In java, if you don't write a constructor, a default constructor will be added automatically for you, and this constructor would be public and takes no argument.
Something like the following:
public ElectricityCalculator () {
}
However, when you define any constructors, the default constructor will be removed. And hence, the only constructor that you have in your class is
public ElectricityCalculator (double ir, double fr, double nod) {
initialReading = ir;
finalReading = fr;
numberOfDays = nod;
}
And therefore
ElectricityCalculator myCalculator = new ElectricityCalculator();
Doesn't match any constructors.
you can simply create the instance after getting the values required to construct the object
ElectricityCalculator myCalculator = new ElectricityCalculator(initialReading, finalReading, numberOfDays);
In addition to Sleiman Jneidi answer, you are calling functions, but dont provide any parameters, as the method definition demands:
double standingCharge = myCalculator.standingCharge();
need to be changed to:
double standingCharge = myCalculator.standingCharge(10.0); //example for 10 days
same problem in the lines 42, 44, 46, 48 of your code
public ElectricityCalculator (double ir, double fr, double nod);
public double standingCharge (double numberOfDays);
public double costBeforeVAT (double costOfElectricity, double standingCharge);
public double VAT (double costBeforeVAT);
public double totalCost (double costBeforeVAT, double VAT);
The constructor and these methods take arguments but you are trying to call them as if they did not.
For the constructor, you can simply move this line
ElectricityCalculator myCalculator = new ElectricityCalculator();
to after you take input from the user so you can pass in the arguments.
// pass arguments here
// v v v
... = new ElectricityCalculator( initialReading , finalReading , numberOfDays );
For the other methods you need to be passing in the results of interim calculations. For example VAT(...) takes a costBeforeVAT which I assume should be the return value of costBeforeVAT(... , ...).
double costBeforeVAT = ...;
// pass argument here
// v
double VAT = myCalculator.VAT( costBeforeVAT );
Note that in some cases you probably do not need these methods to have certain parameters, for example
public double standingCharge () {
return numberOfDays * 0.25;
}
because numberOfDays was already a member of the class ElectricityCalculator and
public double costBeforeVAT () {
return costOfElectricity() + standingCharge();
}
because these methods can be called directly instead of asking for their results to be passed in.
Related: "Passing Information to a Method or a Constructor".