Display all iterations of for loop - java

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

Related

Why is my change calculator not working for coins?

I'm trying to make a program that calculates tax and what change needs to be given back, but for some reason, it doesn't tell me what coins to give back. The code tells me which bills I would need to give back, but the coins that are in the decimals don't work. I've tried looking all over stack exchange for a solution, but if I'm being honest, I'm not really sure what to even look for in the first place, so I haven't found a solution. I'm also new to Java and text-based coding in general, so any feedback is appreciated!
Here is my code:
import java.util.*;
public class Decisions1 {
static String taskValue = "C1";
public static void main(String[] args) {
//initiates the scanner
Scanner myInput = new Scanner(System.in);
//creates the variables for the total
double total1 = 0;
//asks for the total cost of all goods
System.out.println("Please enter the total cost of all goods. This program will add tax and calculate the change you must give back to the customer.");
total1 = myInput.nextDouble();
//performs calculations for tax
double tax2 = (total1*1.13);
double tax1 = (double) Math.round(tax2 * 100) / 100;
//creates variable for amount paid
double paid1 = 0;
//prints info to the user and asks how much cash they received
System.out.println("You entered $" + total1 + "\n" + "Total with tax = $" + tax1 + "\n" + "Please enter how much cash was paid by the customer. The amount of change owed to the customer will be displayed.");
paid1 = myInput.nextDouble();
//checks if customer has paid enough
if (tax1 > paid1) {
double owed1 = (tax1-paid1);
System.out.println("The customer still owes $" + owed1 + "!");
} else if (tax1 == paid1) { //checks if the customer has given exact change
System.out.println("The customer has paid the exact amount. You don't have to give them any change.");
} else if (tax1 < paid1) {
//starts change calculations
//variables for money units
double oneHundred = 100;
double fifty = 50;
double twenty = 20;
double ten = 10;
double five = 5;
double toonie = 2;
double loonie = 1;
double quarter = 0.25;
double dime = 0.10;
double nickel = 0.05;
double penny = 0.01;
//variable for change owed (rounded to 2 decimal places
double change1 = Math.round((paid1-tax1)*100)/100;
//calculates remainder
double oneHundredMod = (change1 % oneHundred);
//divides and removes decimal places
double oneHundredOwed = (change1 / oneHundred);
String oneHundredOwed1 = String.valueOf((int) oneHundredOwed);
//does the same thing for fifty
double fiftyMod = (oneHundredMod % fifty);
double fiftyOwed = (oneHundredMod / fifty);
String fiftyOwed1 = String.valueOf((int) fiftyOwed);
//twenties
double twentyMod = (fiftyMod % twenty);
double twentyOwed = (fiftyMod / twenty);
String twentyOwed1 = String.valueOf((int) twentyOwed);
//tens
double tenMod = (twentyMod % ten);
double tenOwed = (twentyMod / ten);
String tenOwed1 = String.valueOf((int) tenOwed);
//fives
double fiveMod = (tenMod % five);
double fiveOwed = (tenMod / five);
String fiveOwed1 = String.valueOf((int) fiveOwed);
//toonies
double tooniesMod = (fiveMod % toonie);
double tooniesOwed = (fiveMod / toonie);
String tooniesOwed1 = String.valueOf((int) tooniesOwed);
//loonies
double looniesMod = (tooniesMod % loonie);
double looniesOwed = (tooniesMod / loonie);
String looniesOwed1 = String.valueOf((int) looniesOwed);
//quarters
double quartersMod = (looniesMod % quarter);
double quartersOwed = (looniesMod / quarter);
String quartersOwed1 = String.valueOf((int) quartersOwed);
//dimes
double dimesMod = (quartersMod % dime);
double dimesOwed = (quartersMod / dime);
String dimesOwed1 = String.valueOf((int) dimesOwed);
//nickels
double nickelsMod = (dimesMod % nickel);
double nickelsOwed = (dimesMod / nickel);
String nickelsOwed1 = String.valueOf((int) nickelsOwed);
//and finally, pennies!
double penniesMod = (nickelsMod % penny);
double penniesOwed = (nickelsMod / penny);
String penniesOwed1 = String.valueOf((int) penniesOwed);
System.out.println("TOTAL CHANGE:" + "\n" + "\n" + "$100 Bill(s) = " + oneHundredOwed1 + "\n" + "$50 Bill(s) = " + fiftyOwed1 + "\n" + "$20 Bill(s) = " + twentyOwed1 + "\n" + "$10 Bill(s) = " + tenOwed1 + "\n" + "$5 Bill(s) = " + fiveOwed1 + "\n" + "Toonie(s) = " + tooniesOwed1 + "\n" +"Loonie(s) = " + looniesOwed1 + "\n" + "Quarter(s) = " + quartersOwed1 + "\n" + "Dime(s) = " + dimesOwed1 + "\n" + "Nickel(s) = " + nickelsOwed1 + "\n" + "Pennies = " + penniesOwed1);
}
}//end main
}// end Decisions1

How would I make it so the output will round up to two decimal places?

My code here is working fine but whenever I run it, it doesn't seem to round up and I don't know what to add and where to add it.
package com.mycompany.billofsale;
public class Billofsale {
public static void main(String[] args) {
double s = 12.49;
double p = 20.00;
double t = 0.13;
double result = s * t;
double result2 = s + result;
double result3 = p - (s + result);
System.out.println("The total is "+s
+ "\n The tax is "+result
+ "\n The total cost with tax is "+result2
+ "\n The change is "+result3);
}
}
You need to use DecimalFormat to format all the numbers that you want to print to the decimals that you want.
Try with this code:
double s = 12.49;
double p = 20.00;
double t = 0.13;
double result = s * t;
double result2 = s + result;
double result3 = p - (s + result);
DecimalFormat format = new DecimalFormat(".00");
format.setRoundingMode(RoundingMode.HALF_UP);
System.out.println("The total is " + s + "\n The tax is " +format.format(result) + "\n The total cost with tax is " + format.format(result2)
+ "\n The change is " + format.format(result3));

Interest not updating

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

Grade average in toString

I'm doing the dreaded grade average problem for my class and have run into MANY hiccups, but this one seems to be the major one. I'm not able to pull the calculated average in my method to the toString. Here's the one method:
public void average() {
total = (((quiz1 + quiz2) / 40 * 25) + (midterm / 100 * 35) + (finalExam / 100 * 40));
DecimalFormat dec = new DecimalFormat("#.0");
dec.format(total);
return;
}
And I'm trying to get it here:
public String toString(){
return ("Grade Report:\n" ....+ "Total Score " + total + "\n" ....);
The average method shouldn't set anything - it should just return the average. You can then format this number in your toString method:
public double average() {
return (((quiz1 + quiz2)/40 * 25) +
(midterm/100 * 35) +
(finalExam/100 * 40));
}
public String toString(){
DecimalFormat dec = new DecimalFormat("#.0");
String averageString = dec.format(average();
return ("The average score is " + averageString); // just an example
}
Your average method has declared void as its return type. It should probably actually return the value it calculates:
public String average(){
total = (((quiz1 + quiz2)/40 * 25) + (midterm/100 * 35) + (finalExam/100 * 40));
DecimalFormat dec = new DecimalFormat("#.0");
return dec.format(total);
}
public String toString(){
return ("Grade Report:\n" + average() + "Total Score " + total + "\n" ....);
}
I see two mistakes:
You're not returning the result of your average method, when you probably should be as opposed to storing it into a field. That's easy enough to fix.
You're likely dividing integers; if we can presume that quiz1, quiz2, midterm and finalExam are all int, then you won't get a floating point result back.
The first fix is easy: remove the total field and replace it with a local variable. Then, return the result of the format.
String total = ...
return dec.format(total);
Next, to ensure you don't divide ints, place some decimals in your quotient.
String total = (((quiz1 + quiz2) / 40.0 * 25) + (midterm / 100.0 * 35) + (finalExam / 100.0 * 40));

Java, format double as dollar value

I am writing a simple loan calculator for a class. I am attempting to have the amounts return in dollar form. I have found system.out.printf(); but cannot seem to make it work properly.
Here is the current code: (I am also aware it doesn't work correctly, will fix later)
public static void calculate() {
annualInterest = (annualInterest * 0.01) / 12; //percentage to decimal then to month interest %
term = term * 12;
double payment = amtBorrowed * annualInterest;
double temp = 1/(1 + annualInterest);
temp = Math.pow(temp,term);
temp = 1 - temp;
payment = payment / temp;
double Interest = amtBorrowed * annualInterest;
double principal = payment - Interest;
System.out.println("Your monthly payment is " + payment);
System.out.println(" | Interest | principal");
System.out.println("Month 1 :" +" "+ Interest + " " + principal);
for (int i = 2; i < term + 1; i ++){
System.out.print("Month "+ i + " :");
amtBorrowed = amtBorrowed - (Interest + principal);
payment = amtBorrowed * annualInterest;
temp = 1/(1 + annualInterest);
temp = Math.pow(temp,term);
temp = 1 - temp;
payment = payment / temp;
Interest = amtBorrowed * annualInterest;
principal = payment - Interest;
System.out.println(" " + Interest + " " + principal);
}
}
Output:
Your monthly payment is 4432.061025275802
| Interest | principal
Month 1 : 500.0 3932.0610252758024
Month 2 : 477.839694873621 3757.789681084494
Month 3 : 456.6615479938304 3591.242149217312
Month 4 : 436.4220295077747 3432.0761055985745
Month 5 : 417.079538832243 3279.9643981645363
Month 6 : 398.5943191472591 3134.594374430564
Using printf instead
System.out.printf("Your monthly payment is $%.2f%n", payment);
This should print
Your monthly payment is $4432.06
Also
System.out.printf(" %8.2f %8.2f%n", Interest, principal);
check if this helps
DecimalFormat.getCurrencyInstance(Locale.US).format(doubleValue)

Categories

Resources