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;
//}
}
Related
I can't figure out how to return the value of finalCost to the main method and have it printed.
import java.util.*;
public class PhonePlan {
private static double basecost = 8.5;
private static double rate = 0.35;
private static double discount = 0.15;
public static void main(String[] args) {
//Scan input for downloadLimit
Scanner scan = new Scanner(System.in);
System.out.print("Enter the download limit in GB: ");
int downloadLimit = scan.nextInt();
// Call other method
calcMonthlyCharge(downloadLimit);
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost));
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
}
Specifically, I can't find how to use the returned value in the "println" line.
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
You call calcMonthlyCharge(downloadLimit),but don't store the returnvalue.
When you call System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
It is unknown what finalcost is, this is a variable which only exist in the scope of calcMonthlyCharge
Either store the returnvalue of calcMonthlyCharge(downloadLimit) and reuse the value to print, or use calcMonthlyCharge(downloadLimit) in your println with downloadLimit as parameter to get a new returnvalue.
I am working on a school project and I am pretty much done but have been stuck in a detail. I am asking the user to enter their starting balance and the interest rate, to make it easier for the user just asking to enter a whole number like 1, 2, 3, etc. Example, if they enter 1000 in starting balance and 9% in the interest rate the result would 1750.00, the expected result is 1007.50 which comes when the user enters .09%, is there a way to change any number the user enters to that so when they enter 9 it transforms it into .09. If you run the code, enter starting balance and rate and then select "M", you will see those numbers. Any ideas will be appreciated, here is the code:
///BankDemo class
import java.util.Scanner;
public class BankDemo {
#SuppressWarnings("unlikely-arg-type")
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
float startingBalance;
float interestRate;
String userInput;
System.out.print("Enter beginning balance :$");
startingBalance = keyboard.nextFloat();
System.out.print("Enter interest rate(whole number) :%");
interestRate = keyboard.nextFloat();
System.out.println("Enter D for deposit" + "\nEnter W to Withdraw" + "\nEnter B for Balance" +
"\nEnter M for Monthly Process" + "\nEnter E to Exit");
userInput = keyboard.next().toLowerCase();
float bal = startingBalance;
float rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
SavingsAccount sv = new SavingsAccount(bal, rate);
if("d".equals(userInput)) {
ba.deposit();
} else if("w".equals(userInput)) {
ba.withdraw();
} else if("b".equals(userInput)) {
ba.totalBalance();
} else if("m".equals(userInput)) {
ba.monthlyProcess();
} else if("e".equals(userInput)) {
ba.exit();
} else {
System.out.print("Error, option to valid");
}
}
}
///BankAccount Class
import java.util.Scanner;
public class BankAccount {
protected float balance;
protected float numDeposits;
protected float numWithdrawals;
protected float annualRate;
protected float monthlyServCharg;
public BankAccount() {
balance = 0;
numDeposits = 0;
numWithdrawals = 0;
annualRate = 0;
monthlyServCharg = 0;
}
public BankAccount(float startingBalance, float interestRate) {
balance = startingBalance;
annualRate = interestRate;
}
public void deposit() {
float valueD;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to deposit :$");
valueD = keyboard.nextFloat();
balance += valueD;
numDeposits++;
}
public void withdraw() {
float valueW;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to withdraw :$");
valueW = keyboard.nextFloat();
if(valueW < 1) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numDeposits++;
}
public void totalBalance() {
System.out.print("Balance is: " + balance);
}
public void calcInterest() {
float monRate = annualRate / 12;
float monInt = balance * monRate;
balance += monInt;
}
public void monthlyProcess() {
calcInterest();
balance -= monthlyServCharg;
numWithdrawals = 0;
numDeposits = 0;
monthlyServCharg = 0;
System.out.printf("Your Balance after Monthly process is: %.2f", balance);
}
public void exit() {
totalBalance();
System.out.print("\nThank you. Bye");
}
}
In your overload constructor, set annualRate equal to (interestRate / 100) to convert it to a percentage. Also, as a side node, you don't need to initialize all the variables on the default constructor because they're initialize to 0 since they're primitive data types.
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".