Been wracking my brain for hours trying to figure this out.
i have the main method which is:
public static void main(String [] args)
{
double payRate;
double grossPay;
double netPay;
int hours;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Pay Roll Program");
printDescription();
System.out.print("Please input the pay per hour: ");
payRate = input.nextDouble();
System.out.println("\nPlease input the pay per hour: ");
hours = input.nextInt();
System.out.println("\n");
netPay = computePaycheck(netPay);
System.out.println("The net pay is $" + (netPay));
System.out.println("We hope you enjoyed this program");
System.exit(0);
and the method that calculated the netPay
public static double computePaycheck(double payRate, int hours)
{
double grossPay = computePaycheck(payRate*hours);
double netPay = (grossPay - (grossPay *.15));
return netPay;
}
But I'm getting the error "computePaycheck(double,int) in PayCheck cannot be applied to (double)"
I sort of understand this, but I can't for the life of me figure out a remedy.
1) You are calling a function with 2 parameters while only passing 1. That will cause a compilation error.
2) When you call computePaycheck from within itself that will loop and cause a stack overflow.
netPay = computePaycheck(netPay);
public static double computePaycheck(double payRate, int hours)
"computePaycheck(double,int) in PayCheck cannot be applied to (double)"
Your method takes two parameters, a double and an int.
You can only call it with those two (you are missing the number of hours in the call).
netPay = computePaycheck(payRate, hours);
double grossPay = payRate*hours;
In your computePaycheck method, you have the following line:
double grossPay = computePaycheck(payRate*hours);
This is passing one parameter (the product of payRate and hours) to the computePaycheck function, which requires two parameters. It looks like you meant to say:
double grossPay = computePaycheck(payRate, hours);
But you will need to be careful! This will cause your program to recur infinitely! You will need to determine how to calculate the gross pay without calling this function, since if you do call it recursively within itself, there is no condition from which it will return.
Your method takes two parameters -- double payRate and int hours, but you are only specifying a double when you call computePaycheck in your main method.
It's not clear what you intend to happen, but the mismatched parameters should let you know what is wrong with your program.
The first statement of your computePaycheck method calls computePaycheck with a single parameter (a double) whereas the computePaycheck takes 2 parameters (a double and an int). That is why your code fails to compile.
If you "fix" this by using double grossPay = computePaycheck(payRate, hours); instead, this will compile BUT you will get infinite recursion! Don't you simply want to do double grossPay = payRate*hours; ?
It's clear that you set 2 parameters but from the main class you are only calling just one parameter. You should find a way to call the 2 parameters at the same time.
Related
This program will calculate the amortization table for a user. The problem is my assignment requires use of subroutines. I totally forgot about that, any ideas on how to modify this to include subroutines?
public class Summ {
public static void main(String args[]){
double loanamount, monthlypay, annualinterest, monthlyinterest, loanlength; //initialize variables
Scanner stdin = new Scanner (System.in); //create scanner
System.out.println("Please enter your loan amount.");
loanamount = stdin.nextDouble(); // Stores the total loan amount to be payed off
System.out.println("Please enter your monthly payments towards the loan.");
monthlypay = stdin.nextDouble(); //Stores the amount the user pays towards the loan each month
System.out.println("Please enter your annual interest.");
annualinterest = stdin.nextDouble(); //Stores the annual interest
System.out.println("please enter the length of the loan, in months.");
loanlength = stdin.nextDouble(); //Stores the length of the loan in months
monthlyinterest = annualinterest/1200; //Calculates the monthly interest
System.out.println("Payment Number\t\tInterest\t\tPrincipal\t\tEnding Balance"); //Creates the header
double interest, principal; //initialize variables
int i;
/* for loop prints out the interest, principal, and ending
* balance for each month. Works by calculating each,
* printing out that month, then calculating the next month,
* and so on.
*/
for (i = 1; i <= loanlength; i++) {
interest = monthlyinterest * loanamount;
principal = monthlypay - interest;
loanamount = loanamount - principal;
System.out.println(i + "\t\t" + interest
+ "\t\t" + "$" + principal + "\t\t" + "$" + loanamount);
}
}
}
any ideas on how to modify this to include subroutines?
Well, you are better off doing it the other way around; i.e. working out what the methods need to be before you write the code.
What you are doing is a form or code refactoring. Here's an informal recipe for doing it.
Examine code to find a sections that perform a specific task and produces a single result. If you can think of a simple name that reflects what the task does, that it a good sign. If the task has few dependencies on the local variables where it currently "sits" that is also a good sign.
Write a method declaration with arguments to pass in the variable values, and a result type to return the result.
Copy the existing statements that do the task into the method.
Adjust the new method body so that references to local variables from the old context are replaced with references to the corresponding arguments.
Deal with the returned value.
Rewrite the original statements as a call to your new method.
Repeat.
An IDE like Eclipse can take care of much of the manual work of refactoring.
However, the real skill is in deciding the best way to separate a "lump" of code into discrete tasks; i.e. a way that will make sense to someone who has to read / understand your code. That comes with experience. And an IDE can't make those decisions for you.
(And did I say that it is easier to design / implement the methods from the start?)
I deleted my previous comment as I answered my own question by reading the associated tags :-)
As an example, define a method like this in your class:
public double CalculateInterest(double loanAmount, double interestRate) {
//do the calculation here ...
}
And then call the method by name elsewhere in your class code e.g.
double amount = CalculateInterest(5500, 4.7);
I've been having trouble with my program. Im supposed to take in 3 variables and plug them into a formula to get an answer. My answer comes out to 0.0 and im not sure what i am doing wrong.
public double compute_cert (int years, double amount, double rate, double certificate)
{
certificate = amount * Math.pow(1 + rate/100, years);
return certificate;
}
The variables rate, amount and years are set up correctly but the answer certificate is always returned as 0.0
public static void main(String[] args)
{
int years = 0;
double amount = 0;
double rate = 0;
double certificate = 0;
char ans;// allows for char
do{
CDProgram C = new CDProgram(years, amount, rate, certificate);
C.get_years();
C.get_amount();
C.get_rate();
C.get_info();
C.compute_cert(years, amount, rate, certificate);
System.out.println ("Would you like to repeat this program? (Y/N)");
ans = console.next().charAt(0);// user enters either Y or y until they wish to exit the program
} while(ans == 'Y'||ans == 'y'); // test of do/while loop
}
Not sure what else to do. Thanks for the help
It looks like you are not assigning the local variables that you are passing into the computation function?
years = C.get_years();
amount = C.get_amount();
rate = C.get_rate();
info = C.get_info();
As it is, the code is just passing 0 for every parameter into your function. Multiplying by 0 will get you 0. If you pass 0, the following line will multiply 0 by some quantity.
certificate = amount * Math.pow(1 + rate/100, years);
It looks like your CDProgram class has fields for years, amount and rate, and your get_ method are prompting the user for the values.
That being the case, it doesn't make sense to pass parameters for them into your calculation method. I would change the method to this.
public double compute_cert () {
certificate = amount * Math.pow(1 + rate/100, years);
return certificate;
}
Then when you call it in main, don't pass any values in. This will just use the values from the fields in the CDProgram class.
Ok. So here's the situation. I have a calculateTax method in my class as you can see below.
But I realize that I have made a big mistake. The "tax" has actually been created as a field at the start of the class.
private double tax;
This should actually be a variable!
But when I create it as a local variable in the method public double calculateTax(double tax) it works, but when I run my tests against it they fail. I get the message
The method calculateTax(double) in the type Salary is not applicable for the arguments ()
So where am I going wrong?
How can I create the tax variable (which can still be returned) without changing the name of the method? The method "calculateTax" needs to stay as that. So where and how can I create the "tax" variable? Thanks in advance!
public double calculateTax() {
if (this.salary <= personalAllowance) { // If the salary is less
// £9440 (personal allowance) and below then no tax will be applied.
}
else if (this.salary <= taxThreshold) { // Else if the salary is less than or equal to the
// tax threshold then do the following:
double taxableSalary = this.salary - personalAllowance; // Salary take away the personal allowance
// equals the taxable salary.
this.tax = taxableSalary * 0.2; // The tax equal the taxable salary * 0.2 (20%)
}
else if (this.salary > 32010) {
double basicRate = taxThreshold * 0.2; // The basic rate tax is the tax threshold * 0.2
double difference = this.salary - taxThreshold; // The difference is the salary - the tax threshold
double highTax = difference - personalAllowance; // The high tax to be calculated is the difference
// take away personal allowance.
double highRate = highTax * 0.4; // The high rate tax is the high tax * the high tax value (40%)
this.tax = highRate + basicRate; // Total tax is the high rate tax (40%) + the basic rate tax (20%)
}
return tax;
Your tax variable is fine.
The compiler thinks that your calculateTax() method expects an argument, a double, representing salary. (I think - maybe the tax rate?) e.g. calculateTax(56789.12);
I don't see that in the code you posted but something is incomplete.
I am doing an assignment for class and we just started making our own methods and what I thought seemed easy enough has become extremely frustration and hoping you can help me wrap my head around it.
First things first and the assignment I am trying to complete is this: make a modular program to calculate monthly payments, seems easy but the few restrictions on this question is as follows
The main method should:
Ask the user for
the loan amount
the annual interest rate ( as a decimal, 7.5% is 0.075 )
the number of months
And
call a method to calculate and return the monthly interest rate (annual rate/12)
call a method to calculate and return the monthly payment
call a method to print a loan statement showing the amount borrowed, the annual interest rate, the number of months, and the monthly payment.
I have gotten to the end of just printing out the loan statement but cant for the life of me the proper way to call it, and make it show up once I run the program :/ so if you can help me understand how its done I would greatly appreciate it.
(I realize that there are probably other mistakes in my code but for right now I would rather just focus on what I need to get done)
import java.util.Scanner;
public class LoanPayment {
/**
* The main method declares the variables in program while getting the user
* info of amount loaned, interest rate of the loan, and the loans duration.
*
* The main method also calls other methods to calculate monthly interest
* monthly payments and the output of the loan statement
*/
public static void main(String[] args)
{
// declare variables
double interest; // interest attributed to the loan
double mInterest; // loans interest divided by 12
int time; // how long the loan was taken out for
double principle; // the amount borrowed
double mPayment; // how much is to be paid each month
double loan;
// initate new scanner class
Scanner keyboard = new Scanner(System.in);
// get user input/information
System.out.println("Hi, Please enter the loan amount here:");
principle = keyboard.nextDouble();
System.out.println("Thanks, now what is the annual interest rate in decimal notation" +
"(example: 7.5% is 0.075:");
interest = keyboard.nextDouble();
System.out.println("now please put in the number of months the loan was taken out for");
time = keyboard.nextInt();
// call method to calculate and return monthly interest rate
mInterest = calcMInterest( interest );
// call method to calculate and return the monthly payment
mPayment = calcMPayment (mInterest, principle, time);
// call method to print loan statement
} // end main ()
/******************************************************************************/
// this class calculates and returns the monthly interest on the loan
public static double calcMInterest( double interest )
{
double mInterest;
mInterest = (interest / 12);
return mInterest;
} // end calcMInterest
/******************************************************************************/
// this class calculates and returns the monthly payment
public static double calcMPayment (double mInterest, double principle, int time)
{
double mPayment;
mPayment = (mInterest * principle) / (1-(1+ Math.pow(mInterest,-time)));
return mPayment;
} // end calcMPayment
/******************************************************************************/
// this class prints a loan statement showing the amount borrowed
// and the amount borrowed, the annual interest rate, the number of months
// and the monthly payment
public static void loanStatement(double principle, double interest, int time, double mPayment)
{
System.out.println(" principle is" + principle);
If // call method to print loan statement is all you have left to do, then this is what you need on the line below it:
loanStatement(principle, interest, time, mPayment);
And it should work fine.
Your other methods have non-void return types, so you put someVariable = yourMethod(yourArguments) in order to accept the return value. However, loanStatement has a void return type. You don't need to do this. You can call it simply as I showed above and it will execute the code in the method.
Though, my personal preference would be to change loanStatement to a String return type and put the print statement in main and print the return of loanStatement. Methods that return Strings almost as easily and are more flexible for future use (for example, if you wanted to allow your program to also write to file, you need two loanStatement methods, or to completely rework loanStatement).
Check out this solution ;)
public class LoanStatement{
public static void main(String []args){
// declare variables
double interest; // interest attributed to the loan
double mInterest; // loans interest divided by 12
int time; // how long the loan was taken out for
double principle; // the amount borrowed
double mPayment; // how much is to be paid each month
double loan;
// initate new scanner class
Scanner keyboard = new Scanner(System.in);
// get user input/information
System.out.println("Hi, Please enter the loan amount here:");
principle = keyboard.nextDouble();
System.out.println("Thanks, now what is the annual interest rate in decimal notation" +
"(example: 7.5% is 0.075:");
interest = keyboard.nextDouble();
System.out.println("now please put in the number of months the loan was taken out for");
time = keyboard.nextInt();
// call method to calculate and return monthly interest rate
mInterest = calcMInterest( interest );
// call method to calculate and return the monthly payment
mPayment = calcMPayment (mInterest, principle, time);
// call method to print loan statement
loanStatement(principle,interest,time,mPayment);
}
// this method calculates and returns the monthly interest on the loan
public static double calcMInterest( double interest )
{
double mInterest;
mInterest = (interest / 12);
return mInterest;
} // end calcMInterest
// this method calculates and returns the monthly payment
public static double calcMPayment (double mInterest, double principle, int time)
{
double mPayment;
mPayment = (mInterest * principle) / (1-(1+ Math.pow(mInterest,-time)));
return mPayment;
} // end calcMPayment
// this class prints a loan statement showing the amount borrowed
// and the amount borrowed, the annual interest rate, the number of months
// and the monthly payment
public static void loanStatement(double principle, double interest, int time, double mPayment)
{
System.out.println(" principle is" + principle);
}
}
I'm stupid.
import java.util.Scanner;
public class ATM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double withdraw = scanner.nextDouble();
double balance = scanner.nextDouble();
int withdraw = 0; int balance;
if (withdraw % 5 == 0 && withdraw<(balance-.5)) {
balance = balance - (withdraw + .5);
System.out.println(balance);
}
else {
System.out.println(balance);
}}}
I'm trying to make it so that the Balance is being subtracted by the Withdrawal amount while incurring a $.50 charge. Unfortunately, it keeps only subtracting the $.50 without subtracting withdraw. Thanks in advance.
FIXED CODE
import java.util.Scanner;
public class ATM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double withdraw = scanner.nextDouble();
double balance = scanner.nextDouble();
if (withdraw % 5 == 0 && withdraw<(balance-.5)) {
balance -= (withdraw + .5);
System.out.println(balance);
}
else {
System.out.println(balance);
}}}
Here is the algorithm https://stackoverflow.com/a/14387552/1083704
You have the same problem - a bug in the complex expression, which includes using unknown types. And you must do the same thing to debug your program -- simplify the oneliner into multiple simple expressions, using intermediate variables. Then you can step-by-step debug your code and observe those intermediate values. Being a programmer means being a hacker and you won't be a hacker without learning debugging.
where are you setting the withdraw variable? I'd look there, it sounds like you're adding .5 to a variable that hasn't been assigned a value greater than 0. A real easy way to test in more complex code would be to set withdraw in your code to say a value of 5 right before using it in your balance equation, that way you can tell if the problem is with your equation, or the withdraw variable, the equation looks solid though. Also, you can do
balance -= (withdraw + .5)
It is fairly hard to debug code when given so little information; but my best guess would be an initialization bug - where withdraw has not been initialized correctly and is just at what I'd assume to be its default value, 0
But to be sure, we'd need to know what withdraw is equal to before your print statement.
Could you add a print statement before adding up the balance like so:
System.out.println(withdraw);
balance -= (withdraw + .5);
System.out.println(balance);
And then see whether withdraw is > 0 at runtime? And if not; check that it gets set to your withdraw value before computing the balance.
Even better would be to post your full code snippet, so we can see ourselves I guess.
N.B. a -= b is shorthand for a = a - b