Proper Formatting - java

I have the program working I just need help cutting off the extra numbers, Im not very skilled at using the printf statements when printing in Java. When I run it I get output like 1225.043 Here is what I have:
import java.util.Scanner;
public class Comparison {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
float amount;
double principal = 1000.00;
double rate;
System.out.println("Enter interest rate");
rate = keyboard.nextDouble();
System.out.println("Year" +" "+ "Amount on deposit");
for(int year = 1; year <= 10; ++year)
{
amount = (float) (principal * Math.pow(1.0 + rate, year));
System.out.println(year+ " "+ amount);
System.out.println();
}
}
}

Try
System.out.printf("%2d %.2f%n", year, amount);
Output:
Enter interest rate
0.1
Year Amount on deposit
1 1100.00
2 1210.00
3 1331.00
4 1464.10
5 1610.51
6 1771.56
7 1948.72
8 2143.59
9 2357.95
10 2593.74

Related

How to add months and days for a simple interest-rate calculation (Java)

I am working on a program for an assignment.
There I got stuck on how to add the days and months for my program.
I can already convert the simple interest into years, but not for months and days:
import java.util.Scanner;
public class SimpleInterest {
public static void main(String[] args) {
double PAmount, ROI, TimePeriod, simpleInterset;
Scanner scanner = new Scanner(System.in);
System.out.print(" Please Enter the Principal Amount : ");
PAmount = scanner.nextDouble();
System.out.print(" Please Enter the Rate Of Interest : ");
ROI = scanner.nextDouble();
System.out.print(" Please Enter the Time Period in Years : ");
TimePeriod = scanner.nextDouble();
simpleInterset = (PAmount * ROI * TimePeriod) / 100;
System.out.println("\n The Simple Interest for Principal Amount " + PAmount + " is = " +
simpleInterset);
}
}
Just ask them separatly then compute the global time
System.out.print(" Please Enter the Principal Amount : ");
double pAmount = Double.parseDouble(scanner.nextLine());
System.out.print(" Please Enter the Rate Of Interest : ");
double rOI = Double.parseDouble(scanner.nextLine());
System.out.print(" Please Enter the Time Period in Years : ");
double years = Double.parseDouble(scanner.nextLine());
System.out.print("And months : ");
double months = Double.parseDouble(scanner.nextLine());
System.out.print("And days");
double days = Double.parseDouble(scanner.nextLine());
double timePeriod = years * months / 12 + days / 365;
double simpleInterset = (pAmount * rOI * timePeriod) / 100;
System.out.println("\n The Simple Interest for Principal Amount " + pAmount + " is = " + simpleInterset);
I'd suggest :
don't define variable before using it if you don't need to do so
use nextLine and parse what you need, you'll avoid suprise with return char
as Java convention, use lowerCamelCase to name your variables

Java ROI Compound Calculator

I have been trying to make a program that takes in:
Initial Value (in billions)
Growth Rate / Year (in billions)
Purchase Price (in billions)
And then is able to calculate the number of years it would take to break even on the investment. I have been able to accomplish this with a brute force algorithm.
I was wondering if there was a way to do this more efficiently (in a way that is more similar to standard algebra).
My Code:
import java.util.Scanner;
public class ReturnOnInvestment {
public static double initialValue;
public static double growthRate;
public static double purchasePrice;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Return on Investment Calculator ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.print(" Starting Value (In Billions): ");
initialValue = input.nextDouble();
System.out.print(" Growth Rate (Per Year in Billions): ");
growthRate = input.nextDouble();
System.out.print(" Purchase Price (In Billions): ");
purchasePrice = input.nextDouble();
input.close();
System.out.println("-----------------------------------------");
System.out.println(" ROI Period: " + calculateYears(0) + " Years");
}
public static double calculateMoney(double years) {
if(years < 1) return 0;
return calculateMoney(years - 1) + initialValue + (growthRate * (years - 1));
}
public static double calculateYears(double years) {
if(calculateMoney(years) >= purchasePrice) return Math.round(years * 100) / 100.0;
return calculateYears(years + 0.01);
}
}
Yes - you can use the logarithm function for that.
Given your Java code you can write:
public static double yearsNeeded(double initialValue, double growthRate, double purchasePrice) {
return Math.log(purchasePrice / initialValue) / Math.log(1 + growthRate);
}
with an example:
public static void main(String[] args) {
System.out.println("Years to go from 100 to 150 with a growth rate of 5%: "
+ yearsNeeded(100, .05, 150));
}
Basically you're trying to solve for "years":
initialValue * (1 + growthRate) ^ years = purchasePrice
where ^ means exponentiation.
You can rewrite that to:
(1 + growthRate) ^ years = purchasePrice / initialValue
which turns into:
years = [1 + growthRate] log (purchasePrice / initialValue)
where the base of the log is "1 + growthRate". And a log of another base is the same as the log in any base divided by the log of the base.

Can anyone help me remove the comma from my output? [duplicate]

This question already has answers here:
how to print a Double without commas
(10 answers)
Closed 7 years ago.
So my code is correctly outputting the compounded interest periodically, but it is putting my output with a comma. Ex: $1,000.00 I would like the answer to be: $1000.00.
Here is my code guys:
package certificatedeposit;
public class CertificateDeposit {
public static void main(String[] args) {
double PV = 1000.00;
System.out.printf("Enter annual rate: ");
java.util.Scanner in = new java.util.Scanner( System.in );
double rate = in.nextDouble( );
double rates = rate / 100 / 12;
System.out.printf("Enter CD term in months: ");
int months = in.nextInt( );
double product = ( 1 + rates);
double exp = Math.pow(product,months);
double fv = PV * exp;
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%,.2f \n", rate, fv);
}
}
I had changed the code for you but as #ajb said in comment, you are getting "," because you have used it while formatting string. For deep understanding read here
package certificatedeposit;
public class CertificateDeposit {
public static void main(String[] args) {
double PV = 1000.00;
System.out.printf("Enter annual rate: ");
java.util.Scanner in = new java.util.Scanner( System.in );
double rate = in.nextDouble( );
double rates = rate / 100 / 12;
System.out.printf("Enter CD term in months: ");
int months = in.nextInt( );
double product = ( 1 + rates);
double exp = Math.pow(product,months);
double fv = PV * exp;
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%.2f \n", rate, fv);
}
}
Remove the comma from the format string for variable fv:
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%.2f \n", rate, fv);
Also here is a discussion about using different (not only comma) symbols for grouping separator.

Separate two loops in java

I should write a program that reads balance and interest rate, and displays the value of the account in ten years with anually, monthly and daily compounds.
I have written for yearly compounding and for monthly. In the second loop for monthly rate, program reads value of "balance" after compounding yearly, while I need it read primary value. How is it possible to separate two loops, so they do not influence each other? Here is my code:
import java.util.Scanner;
public class BankInterest {
public static void main(String []args) {
System.out.println("Please enter your balance: ");
Scanner keyboard = new Scanner(System.in);
double balance = keyboard.nextDouble();
int years = 0;
int months = 0;
int days = 0;
System.out.println("Please enter the ann1ual interest rate in decimal form: ");
double interestRate = keyboard.nextDouble();
while (years<10) {
double interest = balance * interestRate;
balance = balance + interest;
years++;
}
System.out.println("Balance after 10 years with annual interest is " + balance);
while (months<120) {
double interest = balance * interestRate/12;
balance = balance + interest;
months++;
}
System.out.println("Balance after 10 years with monthly interest rate is " + balance);
}
}
When program is run and I input 100 for balance and 0.02 to interest rate, yearly compounding works well and displays:
Balance after 10 years with annual interest is 121.89944199947573
And second loop takes this value as balance and displays:
Balance after 10 years with monthly interest rate is 148.86352955791543
While, if my code was right it should display this number: 122.119943386
You can place both loops in different functions and pass both balance and interesRate as arguments, like below.
import java.util.Scanner;
public class BankInterest {
static public double annualInterest(double balance, double interestRate) {
int years = 0;
while (years < 10) {
double interest = balance * interestRate;
balance = balance + interest;
years++;
}
return balance;
}
static public double monthlyInterest(double balance, double interestRate) {
int months = 0;
while (months < 120) {
double interest = balance * interestRate/12;
balance = balance + interest;
months++;
}
return balance;
}
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your balance: ");
double balance = keyboard.nextDouble();
System.out.println("Please enter the ann1ual interest rate in decimal form: ");
double interestRate = keyboard.nextDouble();
System.out.println("Balance after 10 years with annual interest is " +
annualInterest(balance, interestRate));
System.out.println("Balance after 10 years with monthly interest rate is " +
monthlyInterest(balance, interestRate));
}
}
You need to declare two different variables for initial balance and updated balance so that you can access the original balance in both loops. I have shown this below.
public static void main(String []args) {
System.out.println("Please enter your balance: ");
Scanner keyboard = new Scanner(System.in);
double startingBalance = keyboard.nextDouble();
double finalBalance=0;
int years = 0;
int months = 0;
int days = 0;
System.out.println("Please enter the ann1ual interest rate in decimal form: ");
double interestRateYearly = keyboard.nextDouble();
double interstRateMonthly = interestRateYearly;
double interstRateDayliy = interestRateYearly;
while (years<10) {
double interest = startingBalance * interestRateYearly ;
finalBalance = startingBalance + interest;
years++;
}
System.out.println("Balance after 10 years with annual interest is " + finalBalance);
while (months<120) {
double interest = startingBalance * interstRateMonthly /12;
finalBalance = startingBalance + interest;
months++;
}
System.out.println("Balance after 10 years with monthly interest rate is " + finalBalance);
}
}

Investment code in Java

I have a project where I have to write a program that prompts the user for an initial investment amount and a goal investment amount and calculate how many years it will take to grow from the initial amount to the goal amount with a fixed interest rate (ie: 5 %). (use the WHILE loop). Print out the results from each year. For example, if you chose to invest $1,000 for 5 years:
Year 1 1005
Year 2 1011
Etc:
I was able to compile the java program but I was only able to prompt the user for an initial investment and goal investment with a 5% interest. The output was incorrect. What am I doing incorrect? Here is my code.
import static java.lang.System.out;
import java.util.Scanner;
import java.io.*;
public class Investment_Calculator {//main
public static void main(String[] args) {//begins body
double principal = 1;//initial amount investing
double interest = 1;
double rate = 0.05;//the fixed interest amount
int years = 1;//amout of years it will take to achieve goal
double goal = 1;
double total = 1;
Scanner myScanner = new Scanner(System.in);
System.out.println("*************************************** ");
System.out.println("* Welcome to the Investment Calculator * ");
System.out.println("*************************************** ");
System.out.println ("Enter your initial investment amount: if you want to exit enter 0.");
int inputNumber = myScanner.nextInt();
principal = inputNumber;
if (inputNumber == 0){//if num = 0 exit class
System.exit(0);
}
System.out.println ("Enter your goal investment amount: ");
int inputNumber2 = myScanner.nextInt ();
goal = inputNumber2;
System.out.println ("The fixed interest rate is 5%");
total= principal; // start with our initial amount of money
for (; total < goal; total= (1+interest)*total);
{ System.out.print("The number of years you must invest to meet your goal of $ ");
System.out.print(goal);
System.out.print(" is");
System.out.println(years);
System.out.println(" years");
}
}
}
for (; total < goal; total= (1+interest)*total);
You have a semi-colon at the end of this loop. Remove it.
Because of that, your next set of print statements after for loop becomes an unnamed block: -
{
System.out.print("The number of years you must invest to meet your goal of $ ");
System.out.print(goal);
System.out.print(" is");
System.out.println(years);
System.out.println(" years");
years++; <-- // Increment `years` here.
}
And those will be executed only once.
UPDATE: -
You can use the below code to get the totalInterest for each year and the final output
int years = 1;
while (principal <= goal) {
double totalInterest = principal * rate * years / 100.0;
principal = principal + totalInterest;
System.out.println("Interest amount for year: " + years +
" = " + totalInterest);
years++;
}
System.out.print("The number of years you must invest to meet your goal of $ ");
System.out.print(goal);
System.out.print(" is");
System.out.println(years);
System.out.println(" years");
The semicolon at for(; total < goal; total = (1+interest) * total); is causing problems.
change it to :
for (; total < goal; total= (1+interest)*total)
{
System.out.print("The number of years you must invest to meet your goal of $ ");
System.out.print(goal);
System.out.print(" is");
System.out.print(years);
System.out.println(" years");
}
Replace this with your current for- statement
int year = 0;
for (; total < goal; total= ((1+rate)*total), ++year)
{
...
// whatever you were doing in for loop
}
System.out.println (year);

Categories

Resources