Compounding interest program in Java - java

I'm trying to write this compounding interest program with a do while loop at the end and I cannot figure out how to print out the final amount.
Here is the code I have so far :
public static void main(String[] args) {
double amount;
double rate;
double year;
System.out.println("This program, with user input, computes interest.\n" +
"It allows for multiple computations.\n" +
"User will input initial cost, interest rate and number of years.");
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the initial cost?");
amount = keyboard.nextDouble();
System.out.println("What is the interest rate?");
rate = keyboard.nextDouble();
rate = rate/100;
System.out.println("How many years?");
year = keyboard.nextInt();
for (int x = 1; x < year; x++){
amount = amount * Math.pow(1.0 + rate, year);
}
System.out.println("For " + year + " years an initial " + amount + " cost compounded at a rate of " + rate + " will grow to " + amount);
String go = "n";
do{
System.out.println("Continue Y/N");
go = keyboard.nextLine();
}while (go.equals("Y") || go.equals("y"));
}
}

The trouble is, amount = amount * Math.pow(1.0 + rate, year);. You're overwriting the original amount with the calculated amount. You need a separate value to hold the calculated value while still holding the original value.
So:
double finalAmount = amount * Math.pow(1.0 + rate, year);
Then in your output:
System.out.println("For " + year + " years an initial " + amount +
" cost compounded at a rate of " + rate + " will grow to " + finalAmount);
EDIT: Alternatively, you can save a line, a variable, and just do the calculation inline, as such:
System.out.println("For " + year + " years an initial " + amount +
" cost compounded at a rate of " + rate + " will grow to " +
(amount * Math.pow(1.0 + rate, year)));

Related

How do I output multiple different values of user input in Java?

I would like this program below to capture user input (first product name, then costs), and then output to the console, and ask the user if they would like anything else, and if they do, it will do it again and output the next product and costs.
If the user replies with no, then I want it to output a list of the items by number and name, and then the total costs of how every many items were requested, and then a total overall cost.
Here is my code so far; I want to understand how to get the total overall costs and list each item. I feel like I am very close.
public static void main(String[] args) {
/////////Initialize everything here/////////
Scanner keyboard = new Scanner (System.in);
String nameProd;
String response;
int items = 0;
int costMat;
int hoursReq;
int payPerHr = 15; //cost per hour for only one employee, who is also the owner (me)
double shipping = 13.25; //shipping cost remains constant even with multiple items
//////////////////////////////////////////////////////////////////////////////////
System.out.println("================================="
+ "\nWelcome to Ryan's Computer Store!"
+ "\n=================================");
do{
items++;
//////////////////////////////////////////
System.out.print("Enter product name: ");
nameProd = keyboard.next();
////////////////////////////////////////////////
System.out.print("Enter cost of materials: $");
costMat = keyboard.nextInt();
System.out.print("In hours, how soon would you prefer that this order is completed?: ");
hoursReq = keyboard.nextInt();
//////////////////////////////////////////////////////////////////////////////////////////
System.out.println("===================================================================="
+ "\n============================"
+ "\n>>>>>>Rundown of costs<<<<<<"
+ "\nItem #: " + items
+ "\nItem Name: " + nameProd
+ "\nCost of Materials: $" + costMat
+ "\n===>Hours spent creating the product: " + hoursReq + " hours"
+ "\n===>Employee Pay Per Hour: $" + payPerHr);
int priceMarkup = hoursReq*payPerHr;
//////////////////////////////////////////////////////
System.out.println("Price of product after markup: $"
+ (priceMarkup+costMat));
//////////////////////////////////////////////////////
System.out.println("===>Shipping Fee: $" + shipping);
//////////////////////////////////////////////
int costBeforeShipping = priceMarkup+costMat;
double totAmt = shipping+costBeforeShipping;
//////////////////////////////////////////////////////
System.out.println("Amount to be charged for item #" + items + " (" + nameProd + ")" + ": $" + totAmt
+ "\n============================");
//////////////////////////////////////////////////////////////////////////////
System.out.print("========================================================"
+ "\nIs there anything else that you would like to order?: ");
response = keyboard.next();
}
while
(response.equalsIgnoreCase("yes"));
System.out.println(">>>>>========================================================<<<<<\nTOTAL AMOUNT TO BE CHARGED FOR " + items + " ITEMS: " + "\nShipping (flat fee): " + shipping + "\nSum of Items: ");
}}
You need a list to hold item names and one temporary variable to hold sum of prices. I think below code will help you.
Scanner keyboard = new Scanner (System.in);
String nameProd;
String response;
int items = 0;
int costMat;
int hoursReq;
int payPerHr = 15; //cost per hour for only one employee, who is also the owner (me)
double shipping = 13.25; //shipping cost remains constant even with multiple items
//////////////////////////////////////////////////////////////////////////////////
List<String> orderItems = new ArrayList<>();
double totalPrice=0;
System.out.println("================================="
+ "\nWelcome to Ryan's Computer Store!"
+ "\n=================================");
do{
items++;
//////////////////////////////////////////
System.out.print("Enter product name: ");
nameProd = keyboard.next();
////////////////////////////////////////////////
System.out.print("Enter cost of materials: $");
costMat = keyboard.nextInt();
System.out.print("In hours, how soon would you prefer that this order is completed?: ");
hoursReq = keyboard.nextInt();
//////////////////////////////////////////////////////////////////////////////////////////
System.out.println("===================================================================="
+ "\n============================"
+ "\n>>>>>>Rundown of costs<<<<<<"
+ "\nItem #: " + items
+ "\nItem Name: " + nameProd
+ "\nCost of Materials: $" + costMat
+ "\n===>Hours spent creating the product: " + hoursReq + " hours"
+ "\n===>Employee Pay Per Hour: $" + payPerHr);
orderItems.add(nameProd);
int priceMarkup = hoursReq*payPerHr;
//////////////////////////////////////////////////////
System.out.println("Price of product after markup: $"
+ (priceMarkup+costMat));
//////////////////////////////////////////////////////
System.out.println("===>Shipping Fee: $" + shipping);
//////////////////////////////////////////////
int costBeforeShipping = priceMarkup+costMat;
double totAmt = shipping+costBeforeShipping;
totalPrice+=totAmt;
//////////////////////////////////////////////////////
System.out.println("Amount to be charged for item #" + items + " (" + nameProd + ")" + ": $" + totAmt
+ "\n============================");
//////////////////////////////////////////////////////////////////////////////
System.out.print("========================================================"
+ "\nIs there anything else that you would like to order?: ");
response = keyboard.next();
}
while
(response.equalsIgnoreCase("yes"));
System.out.println(">>>>>========================================================<<<<<\nTOTAL AMOUNT TO BE CHARGED FOR ITEMS: " + orderItems + "\nShipping (flat fee): " + shipping + "\nSum of Items: "+totalPrice);
}

Format to show percentages with decimal points

I need some tips on how to get my 2nd and 4th percentage in a ".5%" format because in my result I get the result correct but it prints in a whole percentage. So instead of it showing 4%, 4.5%, 5%, 5.5%, and 6% it gives. 4%, 4%, 5%, 6%, 6% but it still calculates the result correctly. Its like it doesn't show the 4.5% and 5.5%. Heres the code, it may seem long but its just repetitive numbers. Note aIR2 and aIR4, those are the targets
import java.util.Scanner;
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class MortgageCalculator {
public static void main(String[] args) {
double aIR, mortgageAmount;
int noY;
double aIR1, aIR2, aIR3, aIR4, aIR5;
double mIR1, mIR2, mIR3, mIR4, mIR5;
double mPayment1, mPayment2, mPayment3, mPayment4, mPayment5;
double totAmount1, totAmount2, totAmount3, totAmount4, totAmount5;
double oPay1, oPay2, oPay3, oPay4, oPay5;
double oPaypercent1, oPaypercent2, oPaypercent3, oPaypercent4, oPaypercent5;
//This establishes formats for values
NumberFormat fmt1 = NumberFormat.getPercentInstance();
NumberFormat fmt2 = NumberFormat.getCurrencyInstance();
DecimalFormat fmt3 = new DecimalFormat("0.##");
//This asks user for inputs
Scanner scan = new Scanner(System.in);
System.out.println("Enter the Annual Interest Rate: ");
aIR= scan.nextDouble();
System.out.println("Enter the Number of Years you will Pay: ");
noY = scan.nextInt();
System.out.println("Enter Amount Borrowed from the Bank: ");
mortgageAmount = scan.nextInt();
//These will give annual interest rates depending on range
aIR1 = (aIR - 1)/100;
aIR2 = (aIR - 0.5)/100;
aIR3 = (aIR)/100;
aIR4 = (aIR + 0.5)/100;
aIR5 = (aIR + 1)/100;
//These give rates by month according to which rate being taken
mIR1 = (aIR1 / 12);
mIR2 = (aIR2 / 12);
mIR3 = (aIR3 / 12);
mIR4 = (aIR4 / 12);
mIR5 = (aIR5 / 12);
//This takes the amounts per month
mPayment1 = (mIR1 * mortgageAmount)/(1-(1/Math.pow((1+mIR1),12*noY)));
mPayment2 = (mIR2 * mortgageAmount)/(1-(1/Math.pow((1+mIR2),12*noY)));
mPayment3 = (mIR3 * mortgageAmount)/(1-(1/Math.pow((1+mIR3),12*noY)));
mPayment4 = (mIR4 * mortgageAmount)/(1-(1/Math.pow((1+mIR4),12*noY)));
mPayment5 = (mIR5 * mortgageAmount)/(1-(1/Math.pow((1+mIR5),12*noY)));
//This takes the total amount per year
totAmount1 = mPayment1 * (noY*12);
totAmount2 = mPayment2 * (noY*12);
totAmount3 = mPayment3 * (noY*12);
totAmount4 = mPayment4 * (noY*12);
totAmount5 = mPayment5 * (noY*12);
//This is the overpayment because of interest
oPay1 = totAmount1 - (mortgageAmount);
oPay2 = totAmount2 - (mortgageAmount);
oPay3 = totAmount3 - (mortgageAmount);
oPay4 = totAmount4 - (mortgageAmount);
oPay5 = totAmount5 - (mortgageAmount);
//This is the overpayment percentage
oPaypercent1 = (oPay1/mortgageAmount);
oPaypercent2 = (oPay2/mortgageAmount);
oPaypercent3 = (oPay3/mortgageAmount);
oPaypercent4 = (oPay4/mortgageAmount);
oPaypercent5 = (oPay5/mortgageAmount);
//Begins printing the results in a line
System.out.println("The Mortgage Amount is: "
+ fmt2.format(mortgageAmount));
System.out.println("The Number of Years the Mortgage is Held: " + noY);
System.out.println("Range of Interest Rates: " + fmt1.format(aIR1)
+ " - " + fmt1.format(aIR5));
System.out.println("Interest Rate Monthly Payment Total Payment"
+ " $ Overpayment % Overpayment");
//Prints first interest rate
System.out.println("" + fmt1.format(aIR1) + " " +
fmt2.format(mPayment1) + " " + fmt2.format(totAmount1)
+ " " + fmt2.format(oPay1) + " "
+ fmt1.format(oPaypercent1) + "");
//Prints second interest rate
System.out.println("" + fmt1.format(aIR2) + " " +
fmt2.format(mPayment2) + " " + fmt2.format(totAmount2)
+ " " + fmt2.format(oPay2) + " "
+ fmt1.format(oPaypercent2) + "");
//Prints third interest rate
System.out.println("" + fmt1.format(aIR3) + " " +
fmt2.format(mPayment3) + " " + fmt2.format(totAmount3)
+ " " + fmt2.format(oPay3) + " "
+ fmt1.format(oPaypercent3) + "");
//Prints fourth interest rate
System.out.println("" + fmt1.format(aIR4) + " " +
fmt2.format(mPayment4) + " " + fmt2.format(totAmount4)
+ " " + fmt2.format(oPay4) + " "
+ fmt1.format(oPaypercent4) + "");
//Prints fifth interest rate
System.out.println("" + fmt1.format(aIR5) + " " +
fmt2.format(mPayment5) + " " + fmt2.format(totAmount5)
+ " " + fmt2.format(oPay5) + " "
+ fmt1.format(oPaypercent5) + "");
}
}
If you want a NumberFormat that displays 4% and 4.5%, i.e. percentage values with a single optional fraction digit, do one of the following:
// Option 1
NumberFormat fmt = NumberFormat.getPercentInstance();
fmt.setMaximumFractionDigits(1);
// Option 2
NumberFormat fmt = new DecimalFormat("0.#%");
Formatting the interest rate should be changed to handle decimal percentage values.
import java.util.Scanner;
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class HelloWorld {
public static void main(String[] args) {
double aIR, mortgageAmount;
int noY;
double aIR1, aIR2, aIR3, aIR4, aIR5;
double mIR1, mIR2, mIR3, mIR4, mIR5;
double mPayment1, mPayment2, mPayment3, mPayment4, mPayment5;
double totAmount1, totAmount2, totAmount3, totAmount4, totAmount5;
double oPay1, oPay2, oPay3, oPay4, oPay5;
double oPaypercent1, oPaypercent2, oPaypercent3, oPaypercent4, oPaypercent5;
//This establishes formats for values
NumberFormat fmt1 = new DecimalFormat("0.#%");
//NumberFormat fmt1 = NumberFormat.getPercentInstance();
NumberFormat fmt2 = NumberFormat.getCurrencyInstance();
DecimalFormat fmt3 = new DecimalFormat("0.##");
//This asks user for inputs
Scanner scan = new Scanner(System.in);
System.out.println("Enter the Annual Interest Rate: ");
aIR= scan.nextDouble();
System.out.println("Enter the Number of Years you will Pay: ");
noY = scan.nextInt();
System.out.println("Enter Amount Borrowed from the Bank: ");
mortgageAmount = scan.nextInt();
//These will give annual interest rates depending on range
aIR1 = (aIR - 1)/100;
aIR2 = (aIR - 0.5)/100;
aIR3 = (aIR)/100;
aIR4 = (aIR + 0.5)/100;
aIR5 = (aIR + 1)/100;
//These give rates by month according to which rate being taken
mIR1 = (aIR1 / 12);
mIR2 = (aIR2 / 12);
mIR3 = (aIR3 / 12);
mIR4 = (aIR4 / 12);
mIR5 = (aIR5 / 12);
//This takes the amounts per month
mPayment1 = (mIR1 * mortgageAmount)/(1-(1/Math.pow((1+mIR1),12*noY)));
mPayment2 = (mIR2 * mortgageAmount)/(1-(1/Math.pow((1+mIR2),12*noY)));
mPayment3 = (mIR3 * mortgageAmount)/(1-(1/Math.pow((1+mIR3),12*noY)));
mPayment4 = (mIR4 * mortgageAmount)/(1-(1/Math.pow((1+mIR4),12*noY)));
mPayment5 = (mIR5 * mortgageAmount)/(1-(1/Math.pow((1+mIR5),12*noY)));
//This takes the total amount per year
totAmount1 = mPayment1 * (noY*12);
totAmount2 = mPayment2 * (noY*12);
totAmount3 = mPayment3 * (noY*12);
totAmount4 = mPayment4 * (noY*12);
totAmount5 = mPayment5 * (noY*12);
//This is the overpayment because of interest
oPay1 = totAmount1 - (mortgageAmount);
oPay2 = totAmount2 - (mortgageAmount);
oPay3 = totAmount3 - (mortgageAmount);
oPay4 = totAmount4 - (mortgageAmount);
oPay5 = totAmount5 - (mortgageAmount);
//This is the overpayment percentage
oPaypercent1 = (oPay1/mortgageAmount);
oPaypercent2 = (oPay2/mortgageAmount);
oPaypercent3 = (oPay3/mortgageAmount);
oPaypercent4 = (oPay4/mortgageAmount);
oPaypercent5 = (oPay5/mortgageAmount);
//Begins printing the results in a line
System.out.println("The Mortgage Amount is: "
+ fmt2.format(mortgageAmount));
System.out.println("The Number of Years the Mortgage is Held: " + noY);
System.out.println("Range of Interest Rates: " + fmt1.format(aIR1)
+ " - " + fmt1.format(aIR5));
System.out.println("Interest Rate Monthly Payment Total Payment"
+ " $ Overpayment % Overpayment");
//Prints first interest rate
System.out.println("" + fmt1.format(aIR1) + " " +
fmt2.format(mPayment1) + " " + fmt2.format(totAmount1)
+ " " + fmt2.format(oPay1) + " "
+ fmt1.format(oPaypercent1) + "");
//Prints second interest rate
System.out.println("" + fmt1.format(aIR2) + " " +
fmt2.format(mPayment2) + " " + fmt2.format(totAmount2)
+ " " + fmt2.format(oPay2) + " "
+ fmt1.format(oPaypercent2) + "");
//Prints third interest rate
System.out.println("" + fmt1.format(aIR3) + " " +
fmt2.format(mPayment3) + " " + fmt2.format(totAmount3)
+ " " + fmt2.format(oPay3) + " "
+ fmt1.format(oPaypercent3) + "");
//Prints fourth interest rate
System.out.println("" + fmt1.format(aIR4) + " " +
fmt2.format(mPayment4) + " " + fmt2.format(totAmount4)
+ " " + fmt2.format(oPay4) + " "
+ fmt1.format(oPaypercent4) + "");
//Prints fifth interest rate
System.out.println("" + fmt1.format(aIR5) + " " +
fmt2.format(mPayment5) + " " + fmt2.format(totAmount5)
+ " " + fmt2.format(oPay5) + " "
+ fmt1.format(oPaypercent5) + "");
}
Output
Interest Rate Monthly Payment Total Payment $ Overpayment % Overpayment
4% $1,841.65 $110,499.13 $10,499.13 10.5%
4.5% $1,864.30 $111,858.12 $11,858.12 11.9%
5% $1,887.12 $113,227.40 $13,227.40 13.2%
5.5% $1,910.12 $114,606.97 $14,606.97 14.6%
6% $1,933.28 $115,996.81 $15,996.81 16%

I have a multi-dimensional array of doubles (Double[][]) created in a child class and I need to print this array in parent class

All of my main methods take place in this class:
package wk2individual;
import java.util.Scanner;
public class Wk2Individual {
public static void main(String[] args) {
AnnualPayCalculator aPC = new AnnualPayCalculator();
SalesPerson sP = new SalesPerson();
//System greeting
Scanner sc = new Scanner (System.in);
System.out.println ("Welcome to the Employee Annual Pay calculator!");
//user input
System.out.println("Please enter the name of the first sales employee:");
sP.salesPerson1 = sc.next();
System.out.println ("Please enter " + sP.salesPerson1 + "'s total sales for the year:");
aPC.totalSales1 = sc.nextDouble();
//begin outputs
if (aPC.totalSales1 >= 112000 && aPC.totalSales1 < 140000) {
System.out.println(sP.salesPerson1 + " has earned $" + aPC.total1() + " in "
+ "commissions for the year! " + sP.salesPerson1 + "'s total pay for the "
+ "year will be $" + aPC.total2()); //outputs employees commission and pay if sales meet incentive
}
else if (aPC.totalSales1 >= 140000) {
System.out.println(sP.salesPerson1 + " has earned $" + aPC.total3() + " in "
+ "commissions for the year! " + sP.salesPerson1 + "'s total pay for the "
+ "year will be $" + aPC.total4()); //outputs employees commission and pay if sales exceed targetSales
}
else if (aPC.totalSales1 < 112000) {
System.out.println(sP.salesPerson1 + " will receive a total pay of $" +
aPC.fixedSalary + " for the year. " + sP.salesPerson1 + " did not meet "
+ "the sales incentive to earn commission for the year."); /*outputs employees end of year pay as fixed
salary since the sales amount is less than 80% of the sales target*/
}
//begin the inputs for the second salesperson
System.out.println("Now let's get the name of the second sales employee:");
sP.salesPerson2 = sc.next();
System.out.println("Please enter " + sP.salesPerson2 + "'s total sales for the year:");
aPC.totalSales2 = sc.nextDouble();
//begin outputs
if (aPC.totalSales2 >= 112000 && aPC.totalSales2 < 140000) {
System.out.println(sP.salesPerson2 + " has earned $" + aPC.total5() + " in "
+ "commissions for the year! " + sP.salesPerson2 + "'s total pay for the "
+ "year will be $" + aPC.total6()); //outputs employees commission and pay if sales meet incentive
}
else if (aPC.totalSales2 >= 140000) {
System.out.println(sP.salesPerson2 + " has earned $" + aPC.total7() + " in "
+ "commissions for the year! " + sP.salesPerson2 + "'s total pay for the "
+ "year will be $" + aPC.total8()); //outputs employees commission and pay if sales exceed targetSales
}
else if (aPC.totalSales2 < 112000) {
System.out.println(sP.salesPerson2 + " will receive a total pay of $" +
aPC.fixedSalary + " for the year. " + sP.salesPerson2 + " did not meet "
+ "the sales incentive to earn commission for the year."); /*outputs employees end of year pay as fixed
salary since the sales amount is less than 80% of the sales target*/
}
//This is where I am trying to print the array created in the SalesPerson class
System.out.println("");
System.out.println("Here are both employee's sales in comparison:");
System.out.println(sP.salesPerson1 + "\t" + sP.salesPerson2);
System.out.print(n);
}
}
I created the AnnualPayCalculator class to hold the totals and calculations:
package wk2individual;
public class AnnualPayCalculator
{
double totalSales1, totalSales2, employee1TotalPay, employee2TotalPay;
double fixedSalary = 75000.00;
final double commissionRate = .25;
double salesTarget = 140000;
double accelerationFactor = .3125;
double total1(){
double incentiveCommission = totalSales1 * commissionRate;
return incentiveCommission;
}
double total2(){
double employee1TotalPay = total1() + fixedSalary;
return employee1TotalPay;
}
double total3(){
double targetCommission = totalSales1 * accelerationFactor;
return targetCommission;
}
double total4(){
double employee1TotalPay = total3() + fixedSalary;
return employee1TotalPay;
}
double total5(){
double incentiveCommission = totalSales2 * commissionRate;
return incentiveCommission;
}
double total6(){
double employee2TotalPay = total5() + fixedSalary;
return employee2TotalPay;
}
double total7(){
double targetCommission = totalSales2 * accelerationFactor;
return targetCommission;
}
double total8(){
double employee2TotalPay = total7() + fixedSalary;
return employee2TotalPay;
}
}
Then I created this SalesPerson class in which holds my array:
package wk2individual;
public class SalesPerson {
String salesPerson1, salesPerson2;
public static void main(String[] args) {
AnnualPayCalculator aPC = new AnnualPayCalculator();
Double[][] sales = new Double[2][2];
sales[0][0] = aPC.totalSales1;
sales[0][1] = aPC.totalSales2;
sales[1][0] = aPC.employee1TotalPay;
sales[1][1] = aPC.employee2TotalPay;
printArray(sales);
};
private static void printArray(Double[][] numbers){
for (Double[] n : numbers){
System.out.print(n);
}
}
In the first class I am able to print the totals of the calculations defined in the AnnualPayCalculator class. How can I print the array in the first class?
You probably don't want 2 main methods. When you create an object of SalesPerson in Wk2Individual, the 2d array sales is not being declared because static methods and variables are not part of instances/objects of classes. So what you might want to do is make a non-static method in SalesPerson like this;
public class SalesPerson {
String salesPerson1, salesPerson2;
public void createSales(AnnualPayCalculator aPC) {
// you don't need to create aPC
// AnnualPayCalculator aPC = new AnnualPayCalculator();
Double[][] sales = new Double[2][2];
sales[0][0] = aPC.totalSales1;
sales[0][1] = aPC.totalSales2;
sales[1][0] = aPC.employee1TotalPay;
sales[1][1] = aPC.employee2TotalPay;
printArray(sales);
}
}
Also, you are probably trying to use the values from the aPC object in the Wk2Individual class. But you are creating a new instance of the object instead. So you should pass the old aPC object from Wk2Individual class like this:
System.out.println("");
System.out.println("Here are both employee's sales in comparison:");
System.out.println(sP.salesPerson1 + "\t" + sP.salesPerson2);
sP.createSales(aPC);
This will send the aPC object with all the calculated values to the createSales() of SalesPerson class where your 2d array will be created.
Now you need to print this. To do that create a print method in the SalesPerson class:
private void printArray(Double[][] numbers){
for (Double[] n : numbers){
System.out.print(n);
}
}
But you cannot print an array like that. So do this:
System.out.println(Arrays.toString(n));
In AnnualPayCalculator class you have several methods which use the global variables: employee1TotalPay and employee2TotalPay. For example, the method total2(). In these methods, you are creating yet another variable with the same name. In total2() you are creating employee1TotalPay which shadows the global variable employee1TotalPay. It means that if inside that method you use employee1TotalPay anywhere, it will use the local employee1TotalPay variable (the one you created inside the method). To use the global variable either remove the declaration of the local variable:
employee1TotalPay = total1() + fixedSalary;
or use the this keyword to access the global variables:
this.employee1TotalPay = total1() + fixedSalary;

Displaying an output decimal with 2 places in java

I'm trying to find out why the %.2f declaration when outputting a decimal isn't working in my code, I've checked other similar questions but I can't seem to locate the issue in the specific logic error I'm receiving. When I go to compile my program it compiles fine, I go to run it and everything outputs fine until I get to the final cost where I'm trying to only display that decimal value with 2 decimal places.
I get an exception in thread "main"
Java.util.illegalformatconversionexception f! = Java.lang.string
At java.util.Formatter$formatspecifier.failconversion(Unknown Source)
At java.util.Formatter$formatspecifier.printFloat(Unknown Source)
At java.util.Formatter.format(Unknown Source)
At java.io.printstream.format(Unknown Source)
At java.io.printstream.printf(Unknown Source)
At Cars.main(Cars.java:27)
Here is my code:
import java.util.Scanner;
public class Cars
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int carYear, currentYear, carAge;
double costOfCar, salesTaxRate;
double totalCost;
String carModel;
System.out.println("Please enter your favorite car model.");
carModel = input.nextLine();
System.out.println("Please enter the year of the car");
carYear = input.nextInt();
System.out.println("Please enter the current year.");
currentYear = input.nextInt();
carAge = currentYear - carYear;
System.out.println("How much does the car cost?");
costOfCar = input.nextDouble();
System.out.println("What is the sales tax rate?");
salesTaxRate = input.nextDouble();
totalCost = (costOfCar + (costOfCar * salesTaxRate));
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f",totalCost + " " + " dollars.");
}
}
I'm not exactly sure what's causing the issue.
Try:
System.out.printf("The model of your favorite car is %s, the car is %d years old, the total of the car is %.2f dollars.", carModel, carAge, totalCost);
Or the more readable:
System.out.printf("The model of your favorite car is %s," +
" the car is %d years old," +
" the total of the car is %.2f dollars.",
carModel, carAge, totalCost);
It's because %.2f is replaced with the entire second argument in that method call. The problem is that by specifying f in %.2f, you are saying that the second argument is a float or double. The second argument in this case is totalCost + " " + " dollars." which evaluates to a string.
To fix this problem, you need to make the second argument be a float or double. This can be achieved by moving + " " + " dollars." from the end of the second argument to the end of the first argument, like so:
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f" + " " + " dollars.",totalCost);
You can also remove many of the unnecessary concatenations from that line, resulting in this:
System.out.printf("The model of your favorite car is" + carModel + ", the car is " + carAge + " years old, the total of the car is %.2f dollars.", totalCost);
The variable has to go as a parameter to the System.out.printf() function. The "%.2f" will be replaced by the double value that is passed as the second parameter.
For Example:
System.out.printf("The value is %.2f", value);
The same thing is true for other variable types and for multiple variables,
String str = "The value is: ";
double value = .568;
System.out.printf("%s %.2f", str, value);
This will output: "The value is: .57"

What to do about dialog box being displayed outside of eclipse program

First I'm new to Java and am taking a beginner's course. Is the use of the % symbol in some cases not allowed in eclipse? in my code when I used the printf method if I use only one percent symbol it gives me an error however when I use 2 it works just fine. It runs the way it should but another issue I'm having is this code prints both to the console and in a dialog box and for some reason the dialog box doesn't get displayed in eclipse if i minimize eclipse i see it show up on my desktop. When i try it in Jgrasp this doesn't happen. Any ideas why this happens?
public class Project6
{
public static void main(String[] args)
{
double diamondCost; // Cost of diamond
double settingCost; // Cost of setting diamond
int numOrdered; // Number of diamonds ordered
double baseCost; // settingCost + diamondCost
double totalCost; // Total cost of diamond including labor and tax
double laborCost; // Cost of jewler's labor
double stateTax; // State tax
double luxuryTax; // Luxury tax
double finalAmountDue; // totalCost*numOrdered
double stateRate=0.10;
double luxuryRate=0.20;
double laborRate=0.05;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the cost of the diamond");
diamondCost = keyboard.nextDouble();
System.out.print("Enter the cost of setting the diamond");
settingCost = keyboard.nextDouble();
System.out.print("Enter the amount of diamonds you want to order");
numOrdered = keyboard.nextInt();
baseCost = diamondCost + settingCost;
luxuryTax = calcExtraCost(baseCost, luxuryRate);
stateTax = calcExtraCost(baseCost, stateRate);
laborCost = calcExtraCost(baseCost, laborRate);
totalCost = baseCost+luxuryTax+stateTax+laborCost;
finalAmountDue = calcExtraCost(totalCost, numOrdered);
System.out.println("Jasmine Jewelry:TOTAL COST BREAKDOWN");
System.out.printf("Diamond Cost: ----- $%.2f\n", diamondCost);
System.out.printf("Setting Cost: ----- $%.2f\n", settingCost);
System.out.printf("State Tax # 10%%: ----- $%.2f\n", stateTax);
System.out.printf("Luxury Tax # 20%%: ----- $%.2f\n", luxuryTax);
System.out.printf("Labor Cost # 5%%: ----- $%.2f\n", laborCost);
System.out.printf("Total Price each: ----- $%.2f\n", totalCost);
System.out.println("Number ordered: " + numOrdered);
System.out.printf("Final Amount Due: $%.2f", finalAmountDue);
DecimalFormat formatter = new DecimalFormat("0.00");
JOptionPane.showMessageDialog(null, "Jasmine Jewelry: TOTAL COST BREAKDOWN\n" + "Diamond Cost: ----- $" +
formatter.format(diamondCost) + "\n" +"Setting Cost: ----- $" + formatter.format(settingCost) + "\n" +
"State Tax # 10%: ----- $" + formatter.format(stateTax) + "\n" + "Luxury Tax # 20%: ----- $" +
formatter.format(luxuryTax) + "\n" + "Labor Cost # 5%: ----- $" + formatter.format(laborCost) + "\n" +
"Total cost each: ----- $" + formatter.format(totalCost) + "\n\n" +"Number ordered: " + numOrdered
+ "\n\nTotal Amount Due: $" + formatter.format(finalAmountDue));
keyboard.close(); // To close scanner object
System.exit(0);
} // End main method
static double calcExtraCost(double diamond, double rate)
{
double extraCharge = diamond*rate;
return extraCharge;
} // End method calcExtraCost
} // End class Project6
First of all printf uses % to mark positions which will be filled with variables later on
f.ex. your
System.out.printf("Diamond Cost: ----- $%.2f\n", diamondCost);
will insert the variable diamondCost at the position of the % character. If you want to print a % character you need to use %%.
Second the problem with your MessageDialog seems to be related that the MessageDialog has no parent.
Maybe how to show JOptionPane on the top of all windows is related to that.

Categories