Java instance variables set to 0 - java

I'm new to understand Java, so forgive me for my ignorance. I have compiled the following code:
import java.lang.Math;
public class Main{
double initialBalance;
double interestRate;
double years;
public static final double periodsPerYear = 12;
//constructer
public Main(double balance, double interest, double life){
}
//methods
double getMonthlyPayment(){
return Math.round(initialBalance * ((interestRate/periodsPerYear)+((interestRate/periodsPerYear)/(Math.pow(1+(interestRate/periodsPerYear),periodsPerYear*years)-1)))*100.00)/100.00;
}
//main method
public static void main(String[] args){
double initialBalance = 10000;
double interestRate = 0.05;
double years = 2;
Main loan = new Main( initialBalance, interestRate, years );
System.out.println(initialBalance);
System.out.println(interestRate);
System.out.println(years);
System.out.println(loan.getMonthlyPayment());
}
}
The problem is the line "System.out.println(loan.getMonthlyPayment())" returns 0.0 when I need to to return 438.71. What am I doing wrong?

In your initialization of the object:
Main loan = new Main(initialBalance, interestRate, years);
this constructor is called:
public Main(double balance, double interest, double life){
}
but it doesn't do anything. It's empty. You need to set the instance variables in the constructor, like so:
public Main(double balance, double interest, double life){
this.initialBalance = balance;
this.interestRate = interest;
this.years = life;
}

Related

I don't understand where does $64 comes from

Assume that a gallon of paint cover's about 350 square feet of wall space, ask a user to enter length, width and height. The methods should do the following:
Calculate the wall area for a room
Passes the calculated wall area to another method that calculates and returns the number of gallons of paint needed
Display the number of gallons needed
Computes the price based on a paint price $32 per gallon, assuming that the painter can buy any fraction of a gallon of paint at the same price as a whole gallon.
returns the price to the main method.
The main() method displays the final price. Example: the cost to paint a 15-by-20 room with 10-foot ceilings is $64.
Here us what I did, and I'm failing to get that $64
public static void main(String[] args){
double l,h,w;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the height: ");
h=sc.nextDouble();
System.out.print("Enter the width: ");
w=sc.nextDouble();
System.out.print("Enter the length: ");
l=sc.nextDouble();
disGallons(calArea(h, w, l));
disPrice(price(calGallon(calArea(h, w, l))));
}
public static double calArea(double h,double w, double l){
double area=2*((w*h)+(l*w)+(l*h));
return area;
}
public static double calGallon(double area){
double gallons= area/350;
return gallons;
}
public static void disGallons(double gallons){
System.out.println("Gallons needed: "+gallons);
}
public static double price(double gallon){
final double gallPrice=32;
return (int)(gallPrice*gallon);
}
public static void disPrice(double price){
System.out.println("Total Price is: $"+price);
}
Here's how I'd do it.
package io.duffymo;
/**
* Size the amount of paint needed
* #link ...
*/
public class PaintSizing {
public static final double PRICE_PER_GALLON_USD = 32.0;
public static final double SQ_FEET_PER_GALLON = 350.0;
public static double area(double h, double w, double l) {
return 2.0*(w + l)*h;
}
public static double gallons(double area) {
return area / SQ_FEET_PER_GALLON;
}
public static double price(double gallons) {
return gallons * PRICE_PER_GALLON_USD;
}
}
It's never too soon to learn about JUnit:
package io.duffymo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class PaintSizingTest {
#Test
public void testSizing() {
// setup
double l = 15.0;
double w = 20.0;
double h = 10.0;
double expectedArea = 700.0;
double expectedGallons = 2.0;
double expectedPrice = 64.0;
// exercise
double actualArea = PaintSizing.area(h, w, l);
double actualGallons = PaintSizing.gallons(actualArea);
double actualPrice = PaintSizing.price(actualGallons);
// assert
Assertions.assertEquals(expectedArea, actualArea, 0.001);
Assertions.assertEquals(expectedGallons, actualGallons, 0.001);
Assertions.assertEquals(expectedPrice, actualPrice, 0.001);
}
}

I am not able to get it do the deductions right on payroll program in java. error I am getting is one of my variables has not been initialized

I am getting an error that says: C:\Users\Jasmi\payroll\src\Payroll.java:68:38
java: variable grossPay might not have been initialized, but I am not sure how to fix it.
public class Payroll {
public String calculateGrossPay;
public String calculateNetPay;
private String name;
private int idNumber;
private double hourlyPayRate;
private double hoursworked;
Payroll(String nameGiven, int idNumbergiven) {
name = nameGiven;
idNumber = idNumbergiven;
hourlyPayRate = 7.15;
hoursworked = 0;
}
public String getName() {
return name;
}
public int getIDNumber() {
return idNumber;
}
public double getHourlyPayrate() {
return hourlyPayRate;
}
public double getHoursWorked() {
return hoursworked;
}
public void setName(String nameGiven) {
name = nameGiven;
}
public void setIDNumber(int idNumbergiven) {
idNumber = idNumbergiven;
}
public void setHourlyPayRate(double hourlypayrategiven) {
hourlyPayRate = hourlypayrategiven;
}
public void setHoursWorked(double hoursworkedgiven) {
hoursworked = hoursworkedgiven;
}
//gross pay plus overtime
public double calculateGrossPay() {
double overtime;
overtime = 0;
double grossPay;
if (hoursworked < 40) grossPay = hourlyPayRate * hoursworked;
else {
overtime = hoursworked - 40;
grossPay = (overtime * 1.5 * hourlyPayRate) + (40 * hourlyPayRate);
}
return grossPay;
}
//deductions
public double calculateNetPay() {
double netPay;
double grossPay;
double deduction = (.2579) * grossPay;
return netPay;
}
}
Here is the second document:
import javax.swing.JOptionPane;
public class PayrollClassTest {
public static void main(String[] args) {
String userInputString;
String userName;
int userId;
double userhourlyPayRate;
double userHoursworked;
userName = JOptionPane.showInputDialog("enter the name of this employee: ");
userInputString = JOptionPane.showInputDialog("Please enter employee ID: ");
userId = Integer.parseInt(userInputString);
userInputString = JOptionPane.showInputDialog("Please enter Hourly Pay Rate: ");
userhourlyPayRate = Double.parseDouble(userInputString);
userInputString = JOptionPane.showInputDialog("Enter the hours worked: ");
userHoursworked = Double.parseDouble(userInputString);
Payroll payroll1 = new Payroll(userName, userId);
payroll1.setHourlyPayRate(userhourlyPayRate);
payroll1.setHoursWorked(userHoursworked);
System.out.println(payroll1.getName() + " has a gross pay of " + payroll1.calculateGrossPay());
System.out.println(payroll1.getName() + " has a net pay of " + payroll1.calculateNetPay());
System.exit(0);
}
private static void calculateGrossPay() {
}
private static void calculateNetPay() {
}
}
I have tried to change deductions to be shown as this:
//deductions
public double calculateNetPay() {
double netPay = 0;
double grossPay = 0;
double deduction = (.2579) * grossPay;
return netPay;
}
}
It does work, but the results do not show the deductions:
Here is an example of the results:
Betty has a gross pay of 13000.0
Betty has a net pay of 0.0
Process finished with exit code 0
This is when I put name as Betty, gross pay as 100, and hours worked as 100. It shows the overtime correctly, but not the deductions.
Any help is greatly appreciated. thanks!
If my understanding of the code is correct then the following is where you are wrong for this piece of code.
public double calculateNetPay() {
double netPay = 0;
double grossPay = 0;
double deduction = (.2579) * grossPay;
return netPay;
}
First: netPay has no value assigned
This method will always return 0.
Reason : The netPay variable is declared and initialized to 0.
What you probably want to do before your return statement is perhaps;
netPay = grossPay - deduction;
I could be wrong in that logic, but I am definitely right when I say that you need to put some value to netPay before you return it.
Second: grossPay has no value assigned
In this method, you multiple .2579 with grossPay, but grossPay is 0 that you have now initialized.
You are assuming that the variable grossPay is shared for the two methods calculateGrossPay and calculateNetPay.
That is not true.
These are both two separate local variables that are declared separately in two different methods and have two different scopes.
You can read more about scope of java variables here:
variable docs from oracle
"in scope" meaning in java : StackOverflow question
My recommendation is to make grossPay a class variable instead of a method variable so that it could be shared between the two methods of the same class instance. (Assuming you are calling calculateGrossPay before calculateNetPay every time, so that grossPay can have the right value assigned to it.)

Can't get desired result on Java program

the problem set asks me to create a bunch of methods in a class Debt.
The method printBalance prints the current balance, and the waitOneYear method grows the debt amount.
The debt is increased by multiplying the balance by the interest rate.
The program should output
120000.0 ,
121200.0 ,
147887.0328416936
after using this test code:
Debt mortgage = new Debt(120000.0, 1.01);
mortgage.printBalance();
mortgage.waitOneYear();
mortgage.printBalance();
int years = 0;
while (years < 20) {
mortgage.waitOneYear();
years = years + 1;
}
mortgage.printBalance();
The code on my Debt class is:
private double balance;
private double interestRate;
public Debt(double initialBalance, double initialInterestRate) {
balance = initialBalance;
interestRate = initialInterestRate;
}
public void printBalance(){
System.out.println(balance);
}
public void waitOneYear(){
this.balance = this.balance + (this.balance*(this.interestRate/100));
}
I'm getting the first 2 integer values from test code correct, however my third value is coming out to be 148194.8253662062.
Can anyone help?
It is a floating point error. This is a good read on the topic https://dzone.com/articles/never-use-float-and-double-for-monetary-calculatio
This is why when dealing with currencies in Java you MUST always use BigDecimal
Here is your code converted to use BigDecimal.
static class Debt {
private BigDecimal balance;
private BigDecimal interestRate;
Debt(double initialBalance, double initialInterestRate) {
balance = BigDecimal.valueOf(initialBalance);
interestRate = BigDecimal.valueOf(initialInterestRate);
}
public void printBalance() {
System.out.println(balance.setScale(10, RoundingMode.HALF_UP));
}
public void waitOneYear() {
this.balance = this.balance.add(this.balance.multiply(this.interestRate.divide(BigDecimal.valueOf(100), RoundingMode.HALF_DOWN)));
}
}
public static void main(String[] args) {
Debt mortgage = new Debt(120000.0, 1.01);
mortgage.printBalance();
mortgage.waitOneYear();
mortgage.printBalance();
int years = 0;
while (years < 20) {
mortgage.waitOneYear();
years = years + 1;
}
mortgage.printBalance();
}

How can I print the first balance, then the new balance?

I've written a small assignment where I've created a TimeDepositAccountand am creating a method to get the current balance, new balance after calculating the interest, and then a withdraw method. I'm stuck on printing the new balance to System.out since for some reason, I'm unable to get the new balance. Second, I want to use a local variable for the withdraw method since in our upcoming test we'll be tested on those, but we never did them in class so I'm unsure as how to go about that.
public class TimeDepositAccount {
//instance fields
private double currentBalance;
private double interestRate;
//Constructors
public TimeDepositAccount(){}
public TimeDepositAccount(double Balance1, double intRate){
currentBalance = Balance1;
interestRate = intRate;
}
//Methods
public double getcurrentBalance(){
return currentBalance;
}
public void newBalance(){
currentBalance = currentBalance * (1 + (interestRate/ 100) );
}
public double getintRate(){
return interestRate;
}
public String toString(){
return "TimeDepositAccount[ currentBalance = "+getcurrentBalance()+",
interestRate = "+getintRate()+"]";
}
public class TimeDepositAccountTester{
public static void main (String[] args){
TimeDepositAccount tda = new TimeDepositAccount(10,2);
double currentBalance = tda.getcurrentBalance();
System.out.println(currentBalance);
tda.newBalance();
System.out.print(currentBalance);
}
}
I wanted the output to first print 10.0, then 10.2, but instead I get 10.0 both times.
You would want to change your main method to the following:
public static void main (String[] args){
TimeDepositAccount tda = new TimeDepositAccount(10,2);
double currentBalance = tda.getcurrentBalance();
System.out.println(currentBalance);
tda.newBalance();
currentBalance = tda.getcurrentBalance();
System.out.print(currentBalance);
}
The variable currentBalance stores what the balance was when you defined it. Changing the balance of tda does not change the value of currentBalance. Thus, to update the value of currentBalance, you need to run currentBalance = tda.getcurrentBalance(); again.

Account and Test Account Interest class

I would like someones expert opinion on both of my account class and the test account interest class. The issue I am facing is that the code from the test account interest class just multiplies on from the previous 12 month compute interest when it is supposed to be used only once.
The issue is in the
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
It is in this method of where the problem is that I should not use the balance but to use a variable that will store the answer but I did not understand the person that very clearly and he was very vague by only stating a variable should be used.
public class Account
{
private double balance; //STATE
private double interestRate; //STATE
private double rate;//STATE
public Account()
{
balance = 0;
interestRate = 0;
}
public Account(double amount, double interestRate)
{
balance = amount;
rate = interestRate;
}
public void deposit(double amount)
{
balance=balance+amount;
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public void setInterest(double rate)
{
balance = balance + balance * rate;
//this.setInterst = setInterest;
//setInterest = InterestRate / 12;
}
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
public double getsetInterest()
{
return rate;
}
public double getBalance()
{
return balance;
}
public void close()
{
balance =0;
}
}
This is my test account interest class:
public class TestAccountInterest
{
public static void main (String[] args)
{
Account acc1 = new Account(100, 0.1);//0.10);
Account acc2 = new Account(133, 0.2); //0.20);
/*************************************
ACC1 ACCOUNT BELOW
*************************************/
//acc1.deposit(100);
//acc1.withdraw(100);
System.out.println(acc1.computeInterest(12));
// //acc1.computeInterest(12);
// System.out.println(acc1.computeInterest(24));
/**************************************
ACC2 ACCOUNT BELOW
**************************************/
acc2.withdraw(100);
acc2.deposit(100);
//acc2.computeInterest(24);
System.out.println(acc2.computeInterest(24));
}
}
This is the final output:
110.00000000000001
191.51999999999998
As you can see for the second one the figure is multiplied by the 12 month compute interest with the 24 month compute interest this stems from the method in the account class:
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
If I take out the balance it still causes and error so I confused on this particular part.
Code,
public double computeInterest(int n) {
balance = balance * (Math.pow((1 + rate), n / 12));
return balance;
}
should be changed to
public double computeInterest(int n) {
return balance * Math.pow(1 + rate, n / 12);
}
You shouldn't change balance field while computing interest. You might like to have a separate method to update balance where you do , balance = balance + computed_interest or something like that.
Also, I have remove unnecessary parenthesis. That was not an error but simply making your code less readable.

Categories

Resources