Displaying an output decimal with 2 places in java - 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"

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);
}

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;

Java - toString Formatting (Formatting Doubles)

The project I am working on requires a bank account balance to be printed using a toString method. I am not allowed to add any methods to my current program, but I need to format my myBalance variable to a double that goes to two decimal places instead of one. In this particular instance my program should be printing 8.03, but it is printing 8.0.
Here is my toString method:
public String toString()
{
return"SavingsAccount[owner: " + myName +
", balance: " + myBalance +
", interest rate: " + myInterestRate +
",\n number of withdrawals this month: " + myMonthlyWithdrawCount +
", service charges for this month: " +
myMonthlyServiceCharges + ", myStatusIsActive: " +
myStatusIsActive + "]";
}
I am very new to Java still, so I would like to know if there is a way to implement %.2f into the string somewhere to format only the myBalance variable. Thank you!
Use String.format(...) for this:
#Override
public String toString() {
return "SavingsAccount[owner: " + myName +
", balance: " + String.format("%.2f", myBalance) +
", interest rate: " + String.format("%.2f", myInterestRate) +
",\n number of withdrawals this month: " + myMonthlyWithdrawCount +
", service charges for this month: " +
myMonthlyServiceCharges + ", myStatusIsActive: " +
myStatusIsActive + "]";
}
or more succinctly:
#Override
public String toString() {
String result = String.format("[owner: %s, balance: %.2f, interest rate: %.2f%n" +
"number of withdrawals this month: %d, service charges for this month: %.2f, " +
"myStatusIsActive: %s]",
myName, myBalance, myInterestRate, myMonthlyWithdrawCount,
myMonthlyServiceCharges, myStatusIsActive);
return result;
}
Note that khelwood asked about my use of "%n" for a new-line token rather than the usual "\n" String. I use %n because this will allow the java.util.Formatter to get a platform specific new-line, useful in particular if I want to write the String to a file. Note that String.format(...) as well as System.out.printf(...) and similar methods use java.util.Formatter in the background so this applies to them as well.
Use String.format()
Example :
Double value = 8.030989;
System.out.println(String.format("%.2f", value));
Output :
8.03

Compounding interest program in 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)));

Java - How to print values to 2 decimal places

I'm coding a simulation of a sports game, and it works fine for the most part; compiles and runs like it should. The directions ask that I I assume that I am supposed to be using printf and %.2f, but whenever I try to incorporate that into my code, it ceases to run properly. Help would be much appreciated!
import java.util.Scanner;
public class Team {
public String name;
public String location;
public double offense;
public double defense;
public Team winner;
public Team(String name, String location) {
this.name = name;
this.location = location;
this.offense = luck();
this.defense = luck();
}
public double luck() {
return Math.random();
}
Team play(Team visitor) {
Team winner;
double home;
double away;
home = (this.offense + this.defense + 0.2) * this.luck();
away = (visitor.offense + visitor.defense) * visitor.luck();
if (home > away)
winner = this;
else if (home < away)
winner = visitor;
else
winner = this;
return winner;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter name and location for home team (on separate lines)");
String homeName = s.next();
String homeLocation = s.next();
Team homeTeam = new Team(homeName, homeLocation);
System.out.println("Enter name and location for home team (on separate lines)");
String awayName = s.next();
String awayLocation = s.next();
Team awayTeam = new Team(awayName, awayLocation);
Team winnerTeam = homeTeam.play(awayTeam);
System.out.printf("Home team is:" + homeName + " from" + homeLocation + " rated" + homeTeam.offense + " (offense) +" + homeTeam.defense + " (defense)" + "\n");
System.out.printf("Away team is:" + awayName + " from" + awayLocation + " rated" + awayTeam.offense + " (offense) +" + awayTeam.defense + " (defense)" + "\n");
System.out.printf("Winner is:" + winnerTeam.name + " from" + winnerTeam.location + " rated" + winnerTeam.offense + " (offense) +" + winnerTeam.defense + " (defense)" + "\n");
}
You have misunderstood the printf method. You do not concatenate strings the way you do in this line and its successors (reformatted for width reasons):
System.out.printf("Home team is:" + homeName +
" from" + homeLocation +
" rated" + homeTeam.offense +
" (offense) +" + homeTeam.defense +
" (defense)" + "\n");
This is like the way an old coworker tried to use PreparedStatements to prevent SQL injection attacks, but constructed the query string by concatenation anyway, making the attempt ineffective. Instead, look at the signature of printf:
public PrintWriter format(String format, Object... args)
The first argument is a format string, which contains static text and format directives beginning with %. In typical use, each format directive corresponds to one argument of the method. Replace the interpolated variables with directives.
Strings are usually formatted with %s: s for string. Doubles are usually formatted with %f: f for float (or double). Characters between the % and the letter are options. So, let's replace the strings you interpolated with directives:
"Home team is: " + "%s" + // Inserted a space.
" from" + "%s" +
" rated" + "%6.2f" + // Six characters, 2 after the decimal.
" (offense) +" + "%6.2f" +
" (defense)" + "%n" // %n means the appropriate way to get a new line
// for the encoding.
Now we put it all together:
System.out.format("Home team is: %s from %s rated %6.2f (offense) + %6.2f (defense)%n",
homeName, homeLocation, homeTeam.offense, homeTeam.defense);
This is a lot simpler. Additionally, another reason to avoid interpolating strings in a format string is that the strings you interpolate may contain a percent sign itself. See what happens if you unguardedly write this:
String salesTax = "5%";
System.out.format("The sales tax is " + salesTax);
That's equivalent to
System.out.format("The sales tax is 5%");
Unfortunately, the percent sign is treated as a format directive, and the format statement throws an exception. Correct is either:
System.out.format("The sales tax is 5%%");
or
String salesTax = "5%";
System.out.format("The sales tax is %s", salesTax);
But now I should ask why you did not take homeName and homeLocation from Team. Certainly they are more relevant to Team than to each other. In fact, you should look up the Formattable interface, and with proper coding you can write:
System.out.format("%s%, homeTeam);
Try this:
public class A {
public static void main(String[] args) {
System.out.println(String.format("%.2f", 12.34123123));
}
}

Categories