Java - How to print values to 2 decimal places - java

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

Related

Is there anyway to format this? The code already runs fine but the formatting will run if the value is too big

I know that I can just use printf to format it but printf is used to print. I want to use the formatting to store the data then call the data to print it outside the do while loop.
#Override
public String toString() {
Scanner input = new Scanner(System.in);
String enter = "", data = "";
double totalCommission = 0.0;
DecimalFormat df = new DecimalFormat();
do {
setTransaction();
setSalesNum();
setName();
setAmount();
setCommission();
setRate();
do {
//prompt user to enter another
System.out.println("Would you like to enter another? [Y/N]");
boolean error = false;
//error prompt if y or n is not entered
enter = input.next();
if (!(enter.equals("n") || enter.equals("N") || enter.equals("y") || enter.equals("Y"))) {
error = true;
System.out.println("Invalid input! Please enter again.\n Would you like to enter another student's mark? [Y/N]");
} else {
error = false;
}
} while (false);
//setting the decimal places
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
//transaction details saved here
data += getTransaction() + "\t" + getSalesNum() + "\t\t" + getName() + "\t\t" + (df.format(getAmount())) + "\t" + " " + getRate() + "%" + "\t\t" + (df.format(getCompute())) + "\n";
totalCommission = totalCommission + getCompute();
} while (enter.equalsIgnoreCase("Y"));
System.out.println("Sales\tCommission");
System.out.println("TNO#\tSALESNO#\tNAME\t\tAMOUNT\t\t" + " " + "COMM RATE\tCOMMISSION");
return String.format(data + "\t\t\t\t\t\t" + " " + "TOTAL COMMISSION\t" + (df.format(totalCommission)));
}
So what I wanted to do is for this part data += getTransaction() + "\t" + getSalesNum() + "\t\t" + getName() + "\t\t" + (df.format(getAmount())) + "\t" + " " + getRate() + "%" + "\t\t" + (df.format(getCompute())) + "\n"; to be formatted inside while (enter.equalsIgnoreCase("Y")); then send data here: return String.format(data + "\t\t\t\t\t\t" + " " + "TOTAL COMMISSION\t" + (df.format(totalCommission)));
I'm sorry but I don't understand what you want to achieve. You may add an input and desired output example.
First of all:
if (!(enter.equals("n") || enter.equals("N") || enter.equals("y") || enter.equals("Y"))) {
if (!(enter.equalsIgnoreCase("n")|| enter.equalsIgnoreCase("y"))) {
You talked about print so you may want to take a look into: https://www.javatpoint.com/java-string-format
Because you mentioned String.format already I guess I misunderstood your question. If you reply back to me I will try to help you.
You wrote that you want to store your data inside that while loop and return it later. In this case, I would add every data to a list and return this list.

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"

Format a decimal in background code java

I have a program which asks for the price of a Shirt in a method called getCost(). When I run my main class, the decimal prints out like $4.5, and doesn't go to 2 decimal places.
In my main class, I created a DecimalFormat object to try and take care of this issue, but it doesn't help. I feel like I either instantiated it wrong, or I am using it wrong. If decimal format does not work, how can I use printf or any other form to fix this issue?
Here is my main class:
public static void main(String[] args)
{
Scanner sc = new Scanner (in);
Object[] Shirts = new Object [6];
Shirt one = new Shirt(10, false, "green" , "stripes", 14.99);
Shirts[0] = one;
Shirt two = new Shirt(9, true, "red", "stripes", 22.90);
Shirts[1] = two;
int sz = 0;
boolean slvs = false;
String clr = " ";
String ptrn = " ";
double cst = 0.0;
DecimalFormat formatter = new DecimalFormat("#.##");
//SHIRT 3
out.println("What is your shirt size::");
sz = sc.nextInt();
out.println();
out.println("How much does your shirt cost::");
cst = sc.nextDouble();
//decimal format here
formatter.format(cst);
out.println();
out.println("Your shirt has sleeves. True or False?");
slvs = sc.nextBoolean();
out.println();
sc.nextLine();
out.println("What is the color of your shirt::");
clr = sc.nextLine();
out.println();
out.println("What pattern does your shirt have::");
ptrn = sc.nextLine();
Shirt three = new Shirt(sz,slvs,clr,ptrn,cst);
sc.nextLine();
Arrays.sort(Shirts);
for(int x = 0; x < Shirts.length - 1; x++)
{
out.println(Shirts[x].toString());
}
Here is the toString() in my Shirt class:
public String toString()
{
String str= "Size: " + getSize() + ", It has sleeves: " + getSleeves() + ", Color: "+ getColor() + ", Pattern: " + getPtrn() + ", Cost: $" + getCost();
return str;
}
The purpose of the formatter is to format the String when you display it, not when you "save" it.
Remove all your formatter.format(whatever), you don't need to format the double when putting it into the shirt (also, you are not doing anything with that line of code).
You need to format when you display the double, in your toString() method:
public String toString()
{
String str= "Size: " + getSize() +
", It has sleeves: " + getSleeves() +
", Color: "+ getColor() +
", Pattern: " + getPtrn() +
", Cost: $" + formatter.format(getCost()); //Format here
return str;
}
Obviously your DecimalFormat must be inside the Shirt class.
Also your pattern isn't correct if you want to always display at least 2 digits. It should be:
DecimalFormat formatter = new DecimalFormat("0.00");
The 0 character is used instead of the pound sign. So 4,3 becomes 4,30.
The problem seems to reside within the toString() method:
public String toString()
{
String str= "Size: " + getSize() + ", It has sleeves: " + getSleeves() + ", Color: "+ getColor() + ", Pattern: " + getPtrn() + ", Cost: $" + getCost();
return str;
}
Since no formatting seems to be done on whatever it is that getCost() yields.
To fix this, try this:
public String toString()
{
String str= "Size: " + getSize() + ", It has sleeves: " + getSleeves() + ", Color: "+ getColor() + ", Pattern: " + getPtrn() + ", Cost: " + NumberFormat.getCurrencyInstance().format(getCost());
return str;
}

Weight Conversion - How to combine various Print Methods into 1 Print Method

I am a novice programmer who is learning Java and though my homework is complete I want to make it neater. I wanted to know if I can combine the following print methods into one and at least combine Kilograms to Pounds and Pounds to Kilograms Methods into one.
Note, I can't use anything more advanced then if statements and loops.
Because this is my first time posting and I want to make sure I provide all answerers with adequate information I have uploaded my Weight Conversion java file to here: Weight Conversion Java file.
Any other advice as to how to simplify the code, or following better code etiquette is welcomed too.
Here are the print statements:
/**
* This method below prints the calculations calculateKG and calculateLBS
*/
public static void printRESULTS1( double dResult1, double dResult2){
// Prints the result of Pounds to Kilograms
System.out.print(dResult1 + " pounds is " + dResult2 + " kilograms.");
}// end method printRESULTS1
/**
* This method below prints the calculations calculateKG and calculateLBS
*/
public static void printRESULTS2( double dResult1, double dResult2){
// Prints the result of Pounds to Kilograms
System.out.print( dResult1 + " kilograms is " + dResult2 + " pounds");
}// end method printRESULTS2
/**
* This method below prints the calculations calculateOZ and calculateLBS
*/
public static void printRESULTS3( double dResultOZ, double dResultLBS){
// Prints the result of Pounds to Kilograms
System.out.print( dResultOZ + " ounces is " + dResultLBS + " pounds");
}// end method printRESULTS3
/**
* This method below prints the calculations calculateOZ and calculateLBS
*/
public static void printRESULTS4( double dResultLBS, double dResultOZ){
// Prints the result of Pounds to Kilograms
System.out.print( dResultLBS + " pounds is " + dResultOZ + " ounces ");
}// end method printRESULTS4
For a start, consider this:
public static void printResults(
double dResultFrom,
String from,
double dResultTo,
String to)
{
System.out.print(dResultFrom + " " + from + " is " + dResultTo + " " + to);
}
Not sure about the whole context you're using it and about your limitations. Of course further refactoring steps are possible. For example:
public static void printResults(
double resultFrom,
String fromDescription,
double resultTo,
String toDescription)
{
String formattedResult = formatResult(
resultFrom,
fromDescription,
resultTo,
toDescription);
System.out.print(formattedResult);
}
public static String formatResult(
double resultFrom,
String fromDescription,
double resultTo,
String toDescription)
{
return formatQuantity(resultFrom, fromDescription)
+ " is "
+ formatQuantity(resultTo, toDescription);
}
public static String formatQuantity(double value, String description)
{
return value + " " + description;
}
Note much less code duplication than in your example, and a clear separation of responsibilities (formatting functions, and printing function). For example, if you had to print results to a file, not to the console, this design would prove more flexible.
Thanks for the help, it made me think harder as to how to simplify the code and organize it better. Also great advice on making sure that the code could be universal as in the print method could be used in another language that isn't English. What really helped was understanding that I can have more then 2 parameters in a Method.
public static void printRESULTS(int nConversion, double dResult1, double dResult2){
//Declare variable
String output = "";
//Pounds to Kilogram output
if (nConversion == 1){
output = dResult1 + " pounds is " + dResult2 + " kilograms.";
System.out.println(output);
}
//Kilograms to Pounds output
else if (nConversion == 2){
output = dResult1 + " kilograms is " + dResult2 + " pounds. ";
System.out.println(output);
}
//Ounces to Pounds output
else if (nConversion == 3){
output = dResult1 + " ounces is " + dResult2 + " pounds. ";
System.out.println(output);
}
//Pounds to Ounces output
else if (nConversion == 4){
output = dResult1 + " pounds is " + dResult2 + " ounces. ";
System.out.println(output);
}

java keeps changing the first zip code

I dont get why when i compile this code i get the incorrect zip code.
John Smith
486 test St.
Yahoo, MA 898 - 2597JohnSmith
486 test St.
Yahoo, MA 898 2597
Code
public class test
{
public static void main(String[] args) {
String firstName = "John";
String lastName = "Smith";
int streetNumber = 486;
String streetName = "test St.";
String city = "Yahoo";
String state = "MA";
int zip = 01602;
int zipplus4 = 2597;
System.out.print(firstName + " " + lastName + "\n" + streetNumber + " " + streetName + "\n" + city + ", " + state + " " + zip + " - " + zipplus4);
System.out.println(firstName + lastName);
System.out.println(streetNumber + " " + streetName);
System.out.println(city + ", " + state + " " + zip + " - " + zipplus4);
}
}
When you specify a number with a leading zero, it gets treated as an Octal (base-8, as opposed to decimal base-10 or hexadecimal base-16).
01602 octal == 898 decimal
Since Java wasn't desgined with Zip codes in mind, to get the desired effect, drop the leading zero, and format it when you print it:
System.out.println(city + ", " + state + " " + new java.text.NumberFormat("00000").format(zip) + " - " + new java.text.NumberFormat("0000").format(zipplus4));
Make those zip codes String instead of int and it'll be fine.
public class test
{
public static void main(String[] args)
{
String firstName = "John";
String lastName = "Smith";
int streetNumber = 486;
String streetName = "test St.";
String city = "Yahoo";
String state = "MA";
String zip = "01602";
String zipplus4 = "2597";
System.out.print(firstName + " " + lastName + "\n" + streetNumber + " " + streetName + "\n" + city + ", " + state + " " + zip + " - " + zipplus4);
System.out.println(firstName + lastName);
System.out.println(streetNumber + " " + streetName);
System.out.println(city + ", " + state + " " + zip + " - " + zipplus4);
}
}
Outcome:
John Smith
486 test St.
Yahoo, MA 01602 - 2597JohnSmith
486 test St.
Yahoo, MA 01602 - 2597
Process finished with exit code 0
I'd also advise you to encapsulate those into sensible objects. Why deal with String primitives when you can use an Address class? Java's object-oriented; better to think in terms of objects.
01602 - this 0 at the beginning means you are using octal rather than decimal numbers. Remove it and you'll be fine :-).
BTW IntelliJ IDEA even displays warning here.
You should use String type for zip and zipplus4.
If you cannot change the type then you can use the following in your println statement
String.format("%05d", zip)
Take off the leading zero~ or make it a string
A Zipcode shouldn't be stored in a numeric datatype because it isn't really something you wnat to do math on, instead store it as a String and it'll work fine.

Categories