Format a decimal in background code java - 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;
}

Related

How to format an output?

(In Java) Write a program that accepts names and formats them as follows: If the input is:
John Anthony Brown
Then the output must be:
Brown, John A.
Here is what I have
int mn;
String input3;
int fn;
int ln;
String firstName;
String lastName;
String middleName;
Scanner scnr = new Scanner(System.in);
String input = scnr.nextLine();
fn = input.indexOf(" ");
firstName = input.substring(0, fn);
middleName = input.substring(fn+1, input.length());
mn = middleName.indexOf(" ");
lastName = input.substring(mn+1, input.length());
System.out.println(lastName + ", " + mn + " " + firstName + ".");
}
I keep trying different things and get weird outputs such as "ry A Lee, 1 Mary." for the input "Marry A Lee"
This topic was never covered in my class and I am very confused.
Because this is homework, I’ll give code fragments:
Firstly, use split() to break up the text into words:
String[] names = input.split(" ");
Then build up your result:
String result = names[2] + ", " + names[0] + ", " + names[1].charAt(0) + ".";
There are more elegant ways of doing it, but this way is arguably the easiest to understand.
You could get fancier by catering for varying numbers of names.
Try something like this:
String[] items = input.split(" ");
//if there are three item in items, then it is the pattern you mentioned
if (items.length == 3) {
System.out.println(items[2] + "," + items[0] + items[1].charAt(0) + ".");
}

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.

Netbeans - Trying to get jCombobox selected item into another JFrame TextArea

Hello wonderful people!
I've relatively new to this java and I'm practicing by creating an online booking system with multiple JFrames (I've heard this could be an issue).
In short, I want to retrieve the value of this jComboBox and display it in a text area on a separate frame. The problem is: How do I undergo this?
private void filmSelecterActionPerformed(java.awt.event.ActionEvent evt) {
if (filmSelecter.getSelectedIndex() == 0)
continueButton.setEnabled(false);
else {
continueButton.setEnabled(true);
}
Second JFrame
private void jQty2ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void reviewButtonActionPerformed(java.awt.event.ActionEvent evt) {
// -------Review Order Button----
double Qty1 = Double.parseDouble(jQty1.getText());
double Qty2 = Double.parseDouble(jQty2.getText());
double Qty3 = Double.parseDouble(jQty3.getText());
double Qty4 = Double.parseDouble(jQty4.getText());
double total, subTotal, ticket1, ticket2, ticket3, ticket4;
String adultPrice = String.format("%.2f", adultprice);
subTotal1.setText(adultPrice);
String studentPrice = String.format("%.2f", studentprice);
subTotal2.setText(studentPrice);
String childPrice = String.format("%.2f", childprice);
subTotal3.setText(childPrice);
String seniorPrice = String.format("%.2f", seniorprice);
subTotal4.setText(seniorPrice);
ticket1 = Qty1 * adultprice;
ticket2 = Qty2 * studentprice;
ticket3 = Qty3 * childprice;
ticket4 = Qty4 * seniorprice;
//subTotal
String sub1 = String.format("£%.2f", ticket1);
subTotal1.setText(sub1);
String sub2 = String.format("£%.2f", ticket2);
subTotal2.setText(sub2);
String sub3 = String.format("£%.2f", ticket3);
subTotal3.setText(sub3);
String sub4 = String.format("£%.2f", ticket4);
subTotal4.setText(sub4);
subTotal = ticket1 + ticket2 + ticket3 + ticket4;
// Total ticket price
String subTotalAll = String.format("£%.2f", subTotal);
jTotalPrice.setText(subTotalAll);
// Receipt
String Title = "\tGreenwich Peninsula Cinema\n\n\n";
String Movie = "Movie Name: " + "\n";
//String MovieDay = "Movie Day" + filmSelecter.getSelectedItem() + "\n";
String MovieTime = "Movie Time: \n";
String Barrier = "=========================================" + "\n";
String Adult = "Adult:" + subTotal1.getText() + "\nNumber of Tickets: " + Qty1 + "\n";
String Student = "Student:" + subTotal2.getText() + "\nNumber of Tickets: " + Qty2 + "\n";
String Child = "Child:" + subTotal3.getText() + "\nNumber of Tickets: " + Qty3 + "\n";
String Senior = "Senior:" + subTotal4.getText() + "\nNumber of Tickets: " + Qty4 + "\n";
String Thanks = "\n\n\tEnjoy the film!";
String ShowReceipt = Barrier + Title + Movie + /*MovieDay +*/ MovieTime + Barrier + Adult + Student + Child + Senior + Thanks + "\n" + Barrier;
filmReceipt.append(ShowReceipt);
}
I hope this helps in anyway.

Converting output to include discounts when applicable

Here's the code I have so far
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Random;
public class TicketInfo
{
static final double STUDENT_DISCOUNT = .80;
static final double FACULTY_STAFF_DISCOUNT = .20;
/**
*Prints date, time, section, row, seat,
*price, cost, final cost with discount.
*
*#param args Command line arguements (not used).
*/
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat("$#,##0.00");
DecimalFormat form = new DecimalFormat("###");
String ticketCode = "";
String event = "";
String date = "";
String time = "";
String section = "";
String row = "";
String seat = "";
String price = "";
String type = "";
String cost = "";
int section1, row1, seat1;
double price1, cost1;
Random generator = new Random();
int random;
System.out.print("Enter your ticket code: ");
ticketCode = userInput.nextLine();
System.out.println();
//Trims any extra white spaces.
ticketCode = ticketCode.trim();
if (ticketCode.length() > 27)
{
//Breaks down the ticket code into parts
type = ticketCode.substring(0, 3);
date = ticketCode.substring(14, 16) + "/"
+ ticketCode.substring(16, 18)
+ "/" + ticketCode.substring(18, 22);
time = ticketCode.substring(22, 24)
+ ":"
+ ticketCode.substring(24, 26);
section = ticketCode.substring(4, 5);
row = ticketCode.substring(5, 7);
seat = ticketCode.substring(8, 9);
price = ticketCode.substring(9, 12);
event = ticketCode.substring(26, ticketCode.length());
cost = ticketCode.substring(10, 14);
//Converts Doubles or Integers in a string into its numeric value.
section1 = Integer.parseInt(section);
row1 = Integer.parseInt(row);
seat1 = Integer.parseInt(seat);
price1 = Double.parseDouble(price);
cost1 = Double.parseDouble(cost);
//Calculate cost based on ticket type
random = generator.nextInt(999999) + 1;
// Print results
System.out.println("Event: " + event + " Date: "
+ date + " Time: " + time);
System.out.println("Section: " + form.format(section1) + " Row: "
+ form.format(row1) + " Seat: " + form.format(seat1));
System.out.println("Price: " + fmt.format(price1) + " Ticket Type: "
+ type + " Cost: " + fmt.format(price1));
System.out.println("Raffle Number: " + random);
}
else
{
System.out.println("Invalid Ticket Code.");
System.out.println("Ticket code must have at least 27 characters.");
}
}
}
Output as of now:
Enter your ticket code: STU01280712500091920151430Auburn vs LSU
Event: Auburn vs LSU Date: 09/19/2015 Time: 14:30
Section: 1 Row: 28 Seat: 7
Price: $125.00 Ticket Type: STU Cost: $125.00
Raffle Number: 939894
I need to make the cost output have discount included. For example, STU type = 80% discount, and F/S type = 20% and REG = no discount.
Goal is to make the cost include the 80% discount for STU ticket type which would make the cost 25.00 for student and 100.00 for faculty with a 20% discount. I think my problem is concerned with constants but I'm not sure since I'm a beginner.
You need to do an "if" condition with the type (LSU, STU, REG)
price1 = Double.parseDouble(price);
if(type.equals("STU")){
price1 = price1 * STUDENT_DISCOUNT;
}
else if(type.equals("LSU")){
price1 = price1 * FACULTY_STAFF_DISCOUNT;
}

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