It is meant to calculate interest and then put that into a table with years, interest, and new balance. For some reason the interest is not being calculated correctly and is not updating.
import java.util.Scanner;
import java.text.*;
public class Interest
{
public static void main(String[] args)
{
printIntro();
Scanner input = new Scanner(System.in);
System.out.print("Enter initial balance: ");
int balanceAmount = input.nextInt();
System.out.print("Enter interest rate: ");
double interestRate = input.nextDouble();
System.out.print("Enter the number of years: ");
int years = input.nextInt();
printTable(years, balanceAmount, interestRate);
}
public static double calcInterest(double balanceAmount, double interestRate, double years)
{
double interest = balanceAmount * Math.pow((1 + interestRate/100),years);
return interest;
}
public static void printRow(int rowNum, double balanceAmount, double interestRate)
{
System.out.println(rowNum + "\t" + balanceAmount + "\t" + "\t" + interestRate + "\t" + "\t" + (balanceAmount + interestRate));
//balanceAmount = (balanceAmount + interestRate);
}
public static void printTable(int numRows, double balanceAmount, double interestRate)
{
System.out.println("Year" + "\t" + "Balance" + "\t" + "\t" + "Interest" + "\t" + "New Balance");
System.out.println("----" + "\t" + "-------" + "\t" + "\t" + "--------" + "\t" + "-----------");
for (int i = 1; i <= numRows; i++)
{
printRow(i, balanceAmount, interestRate);
balanceAmount = (balanceAmount + interestRate);
}
}
public static void printIntro()
{
System.out.println("This program will calculate the interest "
+ "earned on a deposit over a certain amount of years.");
}
}
You should call your business logic to calculate interest as per your business requirement. That totaly depend on your business requirement.
Though for program specific it seems that You need to call your calcInterest method in printTable method, before you call your printRow method as below:
public static void printTable( final int numRows, double balanceAmount, final double interestRate ) {
System.out.println( "Year" + "\t" + "Balance" + "\t" + "\t" + "Interest" + "\t" + "New Balance" );
System.out.println( "----" + "\t" + "-------" + "\t" + "\t" + "--------" + "\t" + "-----------" );
for ( int i = 1; i <= numRows; i++ ) {
double interest = calcInterest( balanceAmount, interestRate, 1 );
printRow( i, balanceAmount, interest );
balanceAmount = ( balanceAmount + interest );
}
}
Also your formula to calculate interest is wrong. it should be
double interest = balanceAmount * Math.pow( ( 1 + interestRate / 100 ), years )-balanceAmount;
It will give out put as below:
This program will calculate the interest earned on a deposit over a certain amount of years.
This program will calculate the interest earned on a deposit over a certain amount of years.
Enter initial balance: 100
Enter interest rate: 10
Enter the number of years: 3
Year Balance Interest New Balance
---- ------- -------- -----------
1 100.0 10.000000000000014 110.00000000000001
2 110.00000000000001 23.100000000000037 133.10000000000005
3 133.10000000000005 44.05610000000007 177.15610000000012
You are not calling calcInterest.
You need to call that under the printRow method before the
System.out.println(rowNum + "\t" + balanceAmount + "\t" + "\t" + interestRate + "\t" + "\t" + (balanceAmount + interestRate));
line
Related
I'm taking a Java class and I've been working on this program that is to calculate credit card balance based on information input through a GUI. In my output Finance Charge, New Balance, and New Payment Due are all coming out as 0. I've tried adding 5 to pinpoint where I messed up and it seems that "balance" isn't being referenced correctly when calculating newBalance. I assume that Finance Charge also has the same issue but fixing balance will help me fix that as well.
//calculates balance
public float calculateBalance()
{
balance = previousBalance + currentPurchases - payments - creditsReturns + lateFees+ 5;
return balance;
}
//sets finance charge
public void setFinanceCharge(float financeCharge)
{
double periodicRate;
periodicRate = .12/12;
float d = (float)periodicRate;
financeCharge = balance * d;
}
//gets finance charge
public float getFinanceCharge()
{
return financeCharge;
}
//Method to calculate new balance
public float calculateNewBalance()
{
//calculate the new balance
newBalance = balance+financeCharge+5;
return newBalance;
}
//setes new payment due
public void setpaymentDue(double newPayment)
{
newPayment = newBalance * .10;
this.paymentDue = (float)newPayment;
}
//gets new payment due
public float getpaymentDue()
{
return paymentDue;
}
//method to display results
public void displayOutput()
{
if (overCreditLimit == 0)
{
JOptionPane.showMessageDialog(null,
"The Customer number is: " + customerNumber + "\n" +
"The Customer name is: " + customerName + "\n" +
"The Credit Limit is: " + creditLimit + "\n" +
"The Previous Balance is: " + previousBalance + "\n" +
"The Current Purchases is: " + currentPurchases + "\n" +
"The Payments is: " + payments + "\n" +
"The Credits/Returns is: " + creditsReturns + "\n" +
"The Late Fees is: " + lateFees + "\n" +
"The Finance Charge is: " + financeCharge + "\n" +
"The New Balance is: " + newBalance + "\n" +
"The New Payment Due is: " + paymentDue + "\n");
}
else
{
overCreditAmount = newBalance - creditLimit - 25;
JOptionPane.showMessageDialog(null, "You are " + overCreditAmount + " dollars over your credit limit,"
+ " a $25 fee has been charged to your new balance");
JOptionPane.showMessageDialog(null,
"The Customer number is: " + customerNumber + "\n" +
"The Customer name is: " + customerName + "\n" +
"The Credit Limit is: " + creditLimit + "\n" +
"The Previous Balance is: " + previousBalance + "\n" +
"The Current Purchases is: " + currentPurchases + "\n" +
"The Payments is: " + payments + "\n" +
"The Credits/Returns is: " + creditsReturns + "\n" +
"The Late Fees is: " + lateFees + "\n" +
"The Finance Charge is: " + financeCharge + "\n" +
"The Amount over Credit Limit is: " + overCreditAmount + "\n" +
"The New Balance is: " + newBalance + "\n" +
"The New Payment Due is: " + paymentDue + "\n");
}
}
One way I see to solve the issue is to run methods within the calculateNewMethod method. For example.
public float calculateNewBalance () {
newBalance = calculateBalance() + getFinanceCharge();
return newBalance;
}
I would also suggest avoiding code where you modify private class varibles and return them within the same method, it make more sense to have one method which modifies it, and one to return the varible.
I created a method that calculates and displays values of simple interest based on the amount of years. I want to show all years so for example if the years is 5, I want to show the value for years 1, 2, 3, 4, 5
This is my code so far
public static String numbers(String method, double principal, double rate, double years) {
double simpleInterest = principal + (principal * (rate / 100) * years);
String interest = "";
for (double digit = 1; digit <= years; digit++) {
if (method.equals("Simple")) {
interest = "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
}
return interest;
}
public static void main(String[] args) {
System.out.print(numbers("Simple", 5000, 5, 5));
}
My output is
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
5.0-->$6250.0
But I want it to also display the previous years like
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
1.0-->$5250.0
2.0-->$5500.0
3.0-->$5750.0
4.0-->$6000.0
5.0-->$6250.0
What do I need to do to display the previous years?
if (method.equals("Simple")) {
interest = "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
in the code above you are reassigning interest if method is equal to "simple". so, the last assigned value is returned.
use += to concatenate new results to interest or just return String[] containing each result as an individual element and then iterate over it.
public static String numbers(String method, double principal, double rate, double years)
{
String interest = "";
for (double digit = 1; digit <= years; digit++)
{
if (method.equals(Simple))
{
double simpleInterest = principal + (principal * (rate / 100) * digit);
interest += "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
}
return interest;
}
You have to calculate simpleInterest for every year simpleInterest = principal + (principal * (rate / 100) * digit); here digit represent year.
and also use += operator to concatenate results to interest and return it.
You can also use string concat() method
Here is the syntax of this method: public String concat(String s).
you can use it like this: interest = interest.concat(digit + "-->$" + simpleInterest + "\n");
public static String numbers(String method, double principal, double rate, double years) {
double simpleInterest = principal + (principal * (rate / 100) * years);
String interest = "";
System.out.println("Principal: $" + principal + ',' + " Rate: " + rate + "\n"+ "Year Simple Interest Amount\n");
for (double digit = 1; digit <= years; digit++) {
if (method.equals("Simple")) {
simpleInterest = principal + (principal * (rate / 100) * digit);
interest += digit + "-->$" + simpleInterest + "\n";
}
}
return interest;
}
public static void main(String[] args) {
System.out.print(numbers("Simple", 5000, 5, 5));
}
Output:
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
1.0-->$5250.0
2.0-->$5500.0
3.0-->$5750.0
4.0-->$6000.0
5.0-->$6250.0
I am a beginner and not tried the following program which is giving me repeated output.. I have to end the program manually in eclipse. Not able to figure out the problem. Please advice. Any other tips are welcome.
import java.util.Scanner;
public class Sales_Amount {
public static void main(String[] args) {
final double Base_Salary = 25000;
double Commission = 0;
double Total_Salary;
double X;
double Y;
Scanner input = new Scanner(System. in );
System.out.print("Enter Sales Amount: ");
double Sales = input.nextDouble();
while (Commission < 25001) {
if (Sales <= 5000); {
Total_Salary = Base_Salary + (0.08 * Sales);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
if (Sales > 5000 && Sales < 10001); {
X = Sales - 5000;
Total_Salary = Base_Salary + (0.08 * 5000) + (0.10 * X);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
if (Sales > 10001); {
Y = Sales - 10000;
Total_Salary = Base_Salary + (.08 * 5000) + (.10 * 10000) + (.12 * Y);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
}
}
}
Add commission++ before the end of the loop.
The balance should take the initial balance and subtract or add the transamt depending on the tcode(1 is a withdraw and 2 is a deposit).
Service charges are $0.10 for a deposit and $0.15 for a check. If a check forces the balance to drop below $500.00, a service charge of $5.00 is assessed but only for the first time this happens. Anytime the balance drops below $50.00, the program should print a warning message. If a check results in a negative balance, an additional service charge of $10.00 should be assessed.
The decimal format for the balance should be "00000.##" for positive and "(00000.##)". I do not know how put the second one.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class Main {
//global variables
CheckingAccount c;
public double balance;
public double totalServiceCharge;
public static void main (String[] args)
{
// defines local variables
String iBalance, transATM, message, transCode;
int tcode;
double transatm, ibalance, currentservicecharge, fee = 0;
// get initial balance from the user
// perform in a loop until the trans code = 0
// get the trans code from the user and process it with appropriate helper method
// When loop ends show final balance to user.
iBalance = JOptionPane.showInputDialog ("Enter the initial balance: ");
ibalance = Double.parseDouble(iBalance);
CheckingAccount c = new CheckingAccount(ibalance);
DecimalFormat df = new DecimalFormat("#####.00");
do
{
transCode = JOptionPane.showInputDialog ("Enter the trans code: ");
tcode = Integer.parseInt(transCode);
if(tcode == 1)
{
transATM = JOptionPane.showInputDialog ("Enter the trans atm: ");
transatm = Double.parseDouble(transATM);
currentservicecharge = 0.15;
message = "Transaction: Check in amount of $" + transatm + "\n" +
"Current balance: " + c.getBalance() + "\n" +
"Service Charge: Check --- charge $ " + currentservicecharge + "\n" +
"Service Charge: " + fee + "\n" +
"Total Service Charge: " + c.getServiceCharge();
JOptionPane.showMessageDialog (null, message + df);
}
else if(tcode == 2)
{
transATM = JOptionPane.showInputDialog ("Enter the trans atm: ");
transatm = Double.parseDouble(transATM);
currentservicecharge = 0.10;
message = "Transaction: Deposit in amount of $" + transatm + "\n" +
"Current balance: " + c.getBalance() + "\n" +
"Service Charge: Check --- charge $ " + currentservicecharge + "\n" +
"Service Charge: " + fee + "\n" +
"Total Service Charge: " + c.getServiceCharge();
JOptionPane.showMessageDialog (null, message + df);
}
}
while (tcode != 0);
message = "Transaction: End" + "\n" +
"Current Balance: " + ibalance + "\n" +
"Total Service Charge: " + c.getServiceCharge() + "\n" +
"Final Balance: " + c.getBalance();
JOptionPane.showMessageDialog (null, message + df);
}
public int getTransCode(int tcode)
{
return tcode;
}
public double getTransAmt(double transatm)
{
return transatm;
}
public double processCheck(double currentservicecharge)
{
return currentservicecharge;
}
public double processDeposit(double currentservicecharge)
{
return currentservicecharge;
}
public double processFee(double fee)
{
return fee;
}
public void setServiceCharge(double currentServiceCharge)
{
totalServiceCharge += currentServiceCharge;
}
public void penatlyCharge(double fee, double currentservicecharge, double transatm, String message, CheckingAccount c)
{
if(c.getBalance() < 500.00)
{
fee = 5.00;
currentservicecharge += fee;
message = "Service Charge: " + fee + "\n" +
"Warning : Balance below $500" ;
}
else if(c.getBalance() < 0.00)
{
fee = 10.00;
currentservicecharge += fee;
message = "Service Charge: " + fee + "\n" +
"Warning : Balance below $0";
}
else if(c.getBalance() < 50.00)
message = "Service Charge: " + fee + "\n" +
"Warning : Balance below $50" ;
}
}
public class CheckingAccount {
private double balance;
private double totalServiceCharge;
public CheckingAccount()
{
balance = 0;
totalServiceCharge = 0;
}
public CheckingAccount(double ibalance)
{
balance = ibalance;
}
public void setBalance(double transamt, int tcode)
{
if(tcode == 1)
{
double newBalance = balance - transamt;
balance = newBalance;
}
else if(tcode == 2)
{
double newBalance = balance + transamt;
balance = newBalance;
}
}
public double getBalance()
{
return balance;
}
public double getServiceCharge()
{
return totalServiceCharge;
}
}
Have you tried something like:
if (amount >= 0.0) {
showMessageDialog(amount);
} else {
showMessageDialog('(' + Math.abs(amount) + ')');
}
That is simplified, but it gets the idea across.
I must convert inches into miles. Then calculate the remaining feet after I calculate the miles. Then calculate the remaining inches after that. The output I'm getting is 19 miles, 19 feet, 7 inches when it should be 19 miles, 2560 feet, 7 inches.
import java.util.Scanner;
/**
* #author abc
* #version 1-28-2014
*/
public class DistanceConverter {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int numOfInches;
System.out.print("Enter the raw measurement in inches: ");
numOfInches = userInput.nextInt();
if (numOfInches < 0) {
System.out.println("Measurement must be non-negative!");
}
int feet = numOfInches / 12;
int miles = feet / 5280;
int remainingFeet = miles % feet;
int remainingInches = numOfInches % 12;
if (numOfInches > 0) {
System.out.println("\n\nMeasurement by combined miles, feet, inches:");
System.out.println("\tmiles: " + miles);
System.out.println("\tfeet: " + remainingFeet);
System.out.println("\tinches " + remainingInches);
System.out.println("\n\n" + numOfInches + " inches = " + miles
+ " miles, " + remainingFeet + " feet, " + remainingInches + " inches");
}
}
}
Try something like this:
if( numOfInches > 0 ) {
int inchesInFeet = 12;
int feetsInMile = 5280;
int inchesInMile = feetsInMile * inchesInFeet;
int miles = numOfInches / inchesInMile;
int remainingInches = numOfInches % inchesInMile;
int feet = remainingInches / inchesInFeet;
remainingInches = remainingInches % inchesInFeet;
System.out.println( "\n\nMeasurement by combined miles, feet, inches:" );
System.out.println( "\tmiles: " + miles );
System.out.println( "\tfeet: " + feet );
System.out.println( "\tinches " + remainingInches );
System.out.println( "\n\n" + numOfInches + " inches = " + miles
+ " miles, " + feet + " feet, " + remainingInches + " inches" );
}