I need to have an outcome like this:
example the user input are principal = 2000, term=6, rate=2%
Period Interest Total Interest Total Balanced<br>
1 6.66 6.66 2006.60
2 6.69 13.35 2013.35
3 6.71 20.06 2020.06
4 6.74 26.80 2026.80
5 6.75 33.55 2033.55
6 6.78 40.33 2040.33
My code is:
import java.io.*;
public class interest
{
public static void main(String[] args)throws Exception
{
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
float p, t, r, total;
int a = 1;
System.out.println("Enter the amount deposited: ");
p = Integer.parseInt(bufferedreader.readLine());
System.out.println("Enter the number of term: ");
t = Integer.parseInt(bufferedreader.readLine());
System.out.println("Enter the interest rate(%): ");
r = Integer.parseInt(bufferedreader.readLine());
System.out.println("Period \t Interest Total Interest Total Balance");
while ( a <= t)
{
System.out.print(" " + a + "\t ");
a++;
{
float R = (float) (r/100)/t;
float interest = (float) p * R;
float totalInt = (float) interest ;
total = p + totalInt;
System.out.println(interest + "\t\t" + totalInt + "\t " + total);
}
}
}
}
but the outcome turns up like this:
Period Interest Total Interest Total Balance
1 6.6666665 6.6666665 2006.6666
2 6.6666665 6.6666665 2006.6666
3 6.6666665 6.6666665 2006.6666
4 6.6666665 6.6666665 2006.6666
5 6.6666665 6.6666665 2006.6666
6 6.6666665 6.6666665 2006.6666
Move your totalInt declaration outside of your while declaration.
You're currently resetting it in every loop, thus it's not actually your total interest but your current interest.
You need to do: totalInt += interest; in the loop.
And you don't need to cast interest to a float again for the increment, as it's already declared as a float.
Also it might be cleaner to do total += interest rather than starting out from your base deposit and incrementing it with your totalInt every time.
And as to your last issue, the formatting, just do something along the lines of:
System.out.printf("%.2f \t\t %.2f \t\t %.2f\n", interest, totalInt, total);
Or take a look at DecimalFormat
I am assuming the question is about the output formating
System.out.printf("%.2f \t\t %.2f \t\t %.2f\n", interest, totalInt, total);
Hi keep float interest before while loop like this
float interest=0;
while ( a <= t)
{
System.out.print(" " + a + "\t ");
a++;
{
float R = (float) (r/100)/t;
interest = interest + (float) p * R;
float totalInt = (float) interest ;
total = p + totalInt;
System.out.println(interest + "\t\t" + totalInt + "\t " + total);
}
}
}
Now Execute it you will get the required output please like if you are satisfied.
Thank You
I think what you want is, change the first line to:
float p, t, r, total, R, interest, totalInt;
and remove float declaration inside loop
Related
double mny = 0;
mny = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the amount of Money", "Money Input", JOptionPane.QUESTION_MESSAGE));
//Check for Tens
System.out.println("The # of Tens is " + (int)(mny/10));
mny = mny%10;
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny) + " $ ");
//Check for Fives
System.out.println("The # of Fives is " + (int)(mny/5));
mny = mny%5;
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny) + " $ ");
//Check for Pennies
System.out.println("The # of Pennies is " + (int)(mny/0.01));
mny = mny%0.01;
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny) + " $ ");
If I input 0.01 it gives me 1 penny, but if I input 15.01 it gives me 1 ten 1 five but no penny.
How should I solve this problem?
The issue you see is why it is highly discouraged to use double for monetary values. Use BigDecimal instead.
public static void printCoins(double mny) {
BigDecimal amount = BigDecimal.valueOf(mny);
//Check for Tens
BigDecimal[] quotientAndRemainder = amount.divideAndRemainder(BigDecimal.TEN);
BigDecimal tens = quotientAndRemainder[0].setScale(0);
amount = quotientAndRemainder[1];
System.out.println("The # of Tens is " + tens);
System.out.println("The remaining amount of money is " + amount.setScale(2, RoundingMode.HALF_EVEN) + " $ ");
//Check for Fives
quotientAndRemainder = amount.divideAndRemainder(BigDecimal.valueOf(5));
BigDecimal fives = quotientAndRemainder[0].setScale(0);
amount = quotientAndRemainder[1];
System.out.println("The # of Fives is " + fives);
System.out.println("The remaining amount of money is " + amount.setScale(2, RoundingMode.HALF_EVEN) + " $ ");
//Check for Pennies
quotientAndRemainder = amount.divideAndRemainder(BigDecimal.valueOf(0.01));
BigDecimal pennies = quotientAndRemainder[0].setScale(0);
amount = quotientAndRemainder[1];
System.out.println("The # of Pennies is " + pennies);
System.out.println("The remaining amount of money is " + amount.setScale(2, RoundingMode.HALF_EVEN) + " $ ");
}
Tests
printCoins(0.01);
printCoins(15.01);
Output
The # of Tens is 0
The remaining amount of money is 0.01 $
The # of Fives is 0
The remaining amount of money is 0.01 $
The # of Pennies is 1
The remaining amount of money is 0.00 $
The # of Tens is 1
The remaining amount of money is 5.01 $
The # of Fives is 1
The remaining amount of money is 0.01 $
The # of Pennies is 1
The remaining amount of money is 0.00 $
The problem you have hit is that floating point number representation is imprecise.
The simplest and easiest way of handling currency is to work with pennies, which are always a whole number, so you can calculate everything using int variables.
This is how banks handle purchase transaction data.
Start with converting user input to an integer number of pennies:
double input = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the amount of Money", "Money Input", JOptionPane.QUESTION_MESSAGE));
int pennies = (int)(input * 100);
Then the rest of your code needs to be converted to working with pennies, which is straightforward.
Because you are assigning the result of each comparison to mny variable, try without them:
double mny = 0;
mny = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the amount of Money", "Money Input", JOptionPane.QUESTION_MESSAGE));
//Check for Tens
System.out.println("The # of Tens is " + (int)(mny/10));
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny % 10) + " $ ");
//Check for Fives
System.out.println("The # of Fives is " + (int)(mny/5));
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny % 5) + " $ ");
//Check for Pennies
System.out.println("The # of Pennies is " + (int)(mny/0.01));
System.out.println("The remaining amount of money is " + new DecimalFormat("0.00").format(mny % 0.01) + " $ ");
This question already has answers here:
How to print a float with 2 decimal places in Java?
(18 answers)
Closed 2 years ago.
I need this specific line to be 2 decimal points.
System.out.println(i + "\t\t" + interest + "\t\t" + principal + "\t\t" + balance);
my entire code is
import java.util.Scanner;
public class assignment5dot22 {
public static void main(String[] args) {
int numberOfYears;
double loanAmount;
double annualInterest;
double monthlyInterest;
double monthlyPayment;
double principal;
double balance;
double interest;
Scanner input = new Scanner(System.in);
System.out.print("Loan Amount: ");
loanAmount = input.nextDouble();
System.out.print("Number of Years: ");
numberOfYears = input.nextInt();
System.out.print("Annual Interest Rate: ");
annualInterest = input.nextDouble();
monthlyInterest = annualInterest / 1200;
monthlyPayment = loanAmount*monthlyInterest / (1 - (Math.pow(1 / (1 + monthlyInterest),
numberOfYears * 12)));
balance = loanAmount;
System.out.println("Monthly Payment: "
+ (monthlyPayment * 100) / 100.0);
System.out.println("Total Payment: "
+ (monthlyPayment * 12 * numberOfYears * 100) / 100.0);
System.out.println("\nPayment#\tInterest\tPrincipal\tBalance");
for (int i = 1; i <= numberOfYears * 12; i++) {
interest = (monthlyInterest * balance);
principal = ((monthlyPayment - interest)*100) / 100.0;
balance = ((balance - principal) * 100) / 100.0;
System.out.println(i + "\t\t" + interest + "\t\t" + principal + "\t\t" + balance);
}
}
}
I'd suggest trying to use String.format() for your output.
e.g.
System.out.println(String.format("%d \t\t %.2f \t\t %.2f \t\t %.2f", i, interest, principal, balance);
String.format allows you use %d and %.2f to explicitly state the format of your data (integer and float respectively)
In these situations you could use String.format or directly use System.out.printf() like so:
System.out.printf("%d \t\t %.2f \t\t %.2f \t\t %.2f\n", i, interest, principal, balance);
For these cases it's more readable and concise.
Problem with my code for calculator - output values not correct
Here is my code, any response would be appreciated.
import java.util.Scanner;
public class Savings {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//ask for initial amount
System.out.print("What is the initial savings amount? ");
double initialAmount = console.nextDouble();
// ask for number of months
System.out.print("What is the number of months to save? ");
int months = console.nextInt();
//ask for interest rate
System.out.print("What is the annual interest rate? ");
double interestRate = console.nextDouble();
//calculate total
double monthlyInterest = ((interestRate/100)*(1/12));
double number1 = (monthlyInterest + 1);
double number2 = Math.pow(number1, months);
double total = (initialAmount*number2);
System.out.println("$" + initialAmount + ", saved for " + months + " months at " + interestRate + "% will be valued at $" + total);
console.close();
}
}
final value ends up being the same value as initial
Change this:
double monthlyInterest = ((interestRate/100)*(1/12));
to
double monthlyInterest = (interestRate / 100) * (1.0 / 12.0);
You're trying to do integer division in floating-point context, so in monthlyInterest you are essentially multiplying interestRate / 100 with 0.
Add d with the numbers to convert them into double and keep the decimal value, this way -
double monthlyInterest = ((interestRate/100d)*(1/12d));
If you do 1/12 with integers, the output will be 0, but with 1/12d it will be 0.08333333333333333
Also, you can get rid of the extra parenthesis -
double monthlyInterest = (interestRate/100d)*(1/12d);
...
double number1 = monthlyInterest + 1;
...
double total = initialAmount * number2;
int single = 0, doub=0, triple=0, homer=0, atbats=0, totalbase, totalhits;
double slug, battingavg;
Scanner sc = new Scanner(System.in);
System.out.print("Enter singles (-1 to end): ");
single = sc.nextInt();
while (single != -1)
{
System.out.print("Enter doubles: ");
doub = sc.nextInt();
System.out.print("Enter triples: ");
triple = sc.nextInt();
System.out.print("Enter home runs: ");
homer = sc.nextInt();
System.out.print("Enter total at bats: ");
atbats = sc.nextInt();
System.out.print("Enter the player's name: ");
String name = sc.next();
totalbase = (single + doub * 2 + triple * 3 + homer * 4);
slug = totalbase / atbats;
battingavg = (single + doub + triple + homer) / atbats;
System.out.println("Player's name is " + name);
System.out.printf("The slugging percentage is %.3f\n", + slug);
System.out.printf("The batting percentage is %.3f\n", + battingavg);
System.out.print("Enter singles (-1 to end): ");
single = sc.nextInt();
}
This program will only output a 1 or a 0 after the calculations. Everything else works fine, but It just doesn't seem to do the calculations.
The problem is that when you do integer divisions, you'll get integer values. Instead use double or float data types. I see slug and battingavg are already doubles, but you're assigning the result of an integer division to them. If you cast at least one of the values in your calculations to a double you should get the output you expect. Example:
slug = totalbase / (double) atbats;
battingavg = (single + doub + triple + homer) / (double) atbats;
When you divide integer values and store the result in a double that is a widening conversion, but the value was calculate as an integer and thus you're widening the integer value.
Change this,
slug = totalbase / atbats;
battingavg = (single + doub + triple + homer) / atbats;
to something like this,
slug = ((double) totalbase / atbats);
battingavg = ((double) (single + doub + triple + homer) / atbats);
to get double values into your double variables.
I've posted this program once before but realized I was overthinking it by adding loops and what not. I've paired it down a bit but still running into problems. The program is supposed to be a change machine. After the user inputs price, the program should round it up to the nearest dollar then output how much change will be dispensed and a count of which coins. The output is completely wrong at this point. I'm very new to programming and I'm at a loss.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price*100);
int paid = (int)(newPrice+1);
int change = (int)(paid - newPrice);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Once newPrice is an int, you can stop casting every line.) Instead of chaining % together, it would be more readable (and less error prone) to subtract off the values you've found:
change -= 25*quarters;
dimes = change / 10;
change -= 10*dimes;
nickels = change / 5;
change -= 5*nickels;
pennies = change;
I think it would help you to understand if you would go through the code by hand and think about what price, newprice, paid, and change are.
newprice is the price round down to the lower dollar.
paid is the cost of the item.
change is the amount you paid minus the cost converted into an integer number of pennies.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price);
int paid = (int)(newPrice+1);
int change = (int)((paid - price) * 100);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
If instruction int paid= (int)(newPrice+1) ; is supposed to be rounding to next dollar, then it should be: int paid= ( newPrice + 99 ) / 100 * 100 ; You don't need to convert to (int) when both operands are already ints. Makes your program slightly illegible. Later, after obtaining the number of quarters by quarters= change / 25 ;(that's correct in your program), you can reduce the amount fromchangewithchange-= quarters * 25 ;`.
This makes calculating dimes exactly the same as quarters, just that using 10 instead of 25. Don't forget reducing the dimes from the pending change again with change-= dimes * 10 ;. You can repeat the process with nickels and the remaining change will be pennies.
If you have any doubt, use a debugger or output each intermediate result with System.out. You can always delete them later once you understand your program's behavior.
This is how I made Java choose what coins I must pay with.
int temp = m;
int quarterCoin = 25;
int x = m/quarterCoin;
m=m-x*quarterCoin;
int dimeCoin = 10;
int z = m/dimeCoin;
m=m-z*dimeCoin;
int nickelCoin = 5;
int y = m/nickelCoin;
m=m-y*nickelCoin;
int pennyCoin = 1;
int w = m/pennyCoin;
m=m-w*pennyCoin;
Instead of giving you the answer/solution to your homework, I am going to help you figure out how to figure it out. :)
In order to adequately debug your software and troubleshoot what's going on, you need to know what your variables are doing. There are two methods:
Attach a debugger - Most IDEs will come with a debugger that will help you accomplish this.
Print out your variables to the console. This is my preferred method. Me and debuggers never have gotten along well together. :)
So, here is what I would do if I were trying to figure your program out:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter Purchase Price: ");
double price = 5.65d;//scan.nextDouble();
int newPrice = (int) (price * 100);
System.out.println("newPrice: " + newPrice);
int paid = (int) (newPrice + 1);
System.out.println("paid: " + paid);
int change = (int) (paid - newPrice);
System.out.println("change: " + change);
int quarters = (int) (change / 25);
int dimes = (int) ((change % 25) / 10);
int nickels = (int) ((change % 25 % 10) / 5);
int pennies = (int) (change % 25 % 10 % 5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Note: Instead of utilizing the scanner, I just manually entered "5.65" into the price variable just to save time)
Which produces the output:
newPrice: 565
paid: 566
change: 1
Dispensing: 0 Quarters,0Dimes,0Nickels,1Pennies.
Program written by Ashley
So, now you can see what your program is doing wrong. Can you spot it?