Formatting perfectly with printf in Java - java

I'm trying to make my program print out a bill of three items with their names quantities and prices. Everything works fine, all I need is how to formate the prices and totals in order to make all the decimals line up everytime, no matter how big the number. Here's my code
import java.util.Scanner;
class AssignmentOneTest {
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
// System.out.printf("$%4.2f for each %s ", price, item);
// System.out.printf("\nThe total is: $%4.2f ", total);
//process for item one
System.out.println("Please enter in your first item");
String item = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity = Integer.parseInt(kb.nextLine());
System.out.println("Please enter in the price of your item");
double price = Double.parseDouble(kb.nextLine());
//process for item two
System.out.println("Please enter in your second item");
String item2 = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity2 = Integer.parseInt(kb.nextLine());
System.out.print("Please enter in the price of your item");
double price2 =Double.parseDouble(kb.nextLine());
double total2 = quantity2*price2;
// System.out.printf("$%4.2f for each %s ", price2, item2);
// System.out.printf("\nThe total is: $%4.2f ", total2);
//process for item three
System.out.println("Please enter in your third item");
String item3 = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity3 = Integer.parseInt(kb.nextLine());
System.out.println("Please enter in the price of your item");
double price3 = Double.parseDouble(kb.nextLine());
double total3 = quantity3*price3;
// System.out.printf("$%4.2f for each %s ", price3, item3);
// System.out.printf("\nThe total is: $%4.2f ", total3);
double total = quantity*price;
double grandTotal = total + total2 + total3;
double salesTax = grandTotal*(.0625);
double grandTotalTaxed = grandTotal + salesTax;
String amount = "Quantity";
String amount1 = "Price";
String amount2 = "Total";
String taxSign = "%";
System.out.printf("\nYour bill: ");
System.out.printf("\n\nItem");
System.out.printf("%28s %11s %11s", "Quantity", "Price", "Total");
//complete item one format
System.out.printf("\n%-30s", item);
System.out.printf("%-10d", (int)quantity);
System.out.printf("%-10.2f", (float)price);
System.out.printf(" " + "%-10.2f", (float)total);
//complete item two format
System.out.printf("\n%-30s", item2);
System.out.printf("%-10d", (int)quantity2);
System.out.printf("%-10.2f", (float)price2);
System.out.printf(" " + "%-10.2f", (float)total2);
//complete item three format
System.out.printf("\n%-30s", item3);
System.out.printf("%-10d", (int)quantity3);
System.out.printf("%-10.2f", (float)price3);
System.out.printf(" " + "%-10.2f", (float)total3);
System.out.printf("\n\n\nSubtotal %47.2f", grandTotal);
System.out.printf("\n6.25 %s sales tax %39.2f", taxSign, salesTax);
System.out.printf("\nTotal %50.2f", grandTotalTaxed);
}
The problem is that every time the prices are the same, everything lines up, but lets say I type in a price of 50.00 and a price of 2.50 for two different items, then the items price and total decimal points don't all line up, please help.

I find that lining up titles and columns is a lot easier if I do the output in a matched pair of functions, one for the titles and one for the data, e.g.:
public static void prLine (String item, int quantity, double price, double total) {
System.out.printf("\n%-20.20s %10d %10.2f %10.2f", item, quantity,
price, total);
}
public static void prTitles () {
System.out.printf("\n%-20s %10s %10s %10s", "Item", "Quantity",
"Price", "Total");
}
You can see that it is easy to get the field widths to correspond nicely this way. Then I can use these functions as follows:
prTitles ();
prLine (item,quantity,price,total);
prLine (item2,quantity2,price2,total2);
prLine (item3,quantity3,price3,total3);
... and I get lined-up output in the style I think you're looking for:
Your bill:
Item Quantity Price Total
first 1 1.50 1.50
second 10 12.50 125.00
third 456 322.00 146832.00
Putting the output code in functions also greatly reduces the number of lines of code in the main() function.

You will have to control this yourself.
Basically I'm thinking there's 2 different ways to handle this.
The first way is to check the length of the output before you output it by converting whatever is necessary into a string, then checking it's length. After you do that you can add in spaces in between the prices to make them line up. Something like this may be able to achieve that, of course integrated however you need it:
int length = String.valueOf(1000d).length();
The second way I'm thinking of is adding tabs between the prices to have it auto line up itself. Of course this way you'll have extra spaces most the time between all of the outputs and you'll have to make sure the item name isn't long enough that you'll need 2 tabs, or more.
Good luck! If you need more clarification, please let me know.
EDIT: To make it a bit better, you can incorporate the length checking above and use printf's width specifier to pad in the spaces. It is a bit better.
// calculate padding based on the length of the output
String format = "%" + padding + "d";
System.out.printf(format, variables);
EDIT2: OOP version of this, it isn't perfect but does it very well :)
EDIT3: Added some comments into the code.
http://pastebin.com/CqvAiQSg

Related

How do I turn a meal order code into stats that a human can read in java?

Pretty simple question, even though it looks long.
I am supposed to write a java code that accepts an input of something like "021250040625Pat John" and turn it into 02 adult meals at 12.50 each (first 6 numbers say that) 4 child meals at 06.25 each (second six) name is Pat John.
I have to total it and add discount but I can do all that, 𝐈 𝐣𝐮𝐬𝐭 𝐝𝐨𝐧'𝐭 𝐤𝐧𝐨𝐰 𝐡𝐨𝐰 𝐭𝐨 𝐫𝐞𝐚𝐝 𝐢𝐧𝐝𝐢𝐯𝐢𝐝𝐮𝐚𝐥 𝐧𝐮𝐦𝐛𝐞𝐫𝐬 𝐟𝐫𝐨𝐦 𝐚 𝐬𝐭𝐫𝐢𝐧𝐠. Any and all help welcome, I'm new to java but understand the basics. Just need help with reading those individual numbers and letters in the input code.
I already have the basics of the code laid out and this// (result is a placeholder)
Scanner userInput = new Scanner(System.in);
System.out.print("Enter your order code: ");
orderCode = userInput.nextDouble();
System.out.println("Name: " + result);
System.out.println("Adult meals: " + result);
System.out.println("Child meals: " + result);
System.out.println("Subtotal: " + result);
System.out.println("15% Discount: " + result);
System.out.println("Total: " + result);
You want to use Scanner#nextLine() to get the order code, and String#substring(int beginIndex, int endIndex) to get the individual numbers. You can convert the numbers from String to int using Integer.praseInt(String s):
Scanner userInput = new Scanner(System.in);
System.out.print("Enter your order code: ");
// Get the entire code using Scanner.nextLine() instead of Scanner.nextDouble()
String code = userInput.nextLine();
// Get the first two characters (the adult meals)
int adultMeals = Integer.parseInt(code.substring(0, 2));
// Get the next four characters separated by a period (the price)
double price = Double.parseDouble(code.substring(2, 4) + "." + code.substring(4, 6));
// Get the next two characters (the child meals)
int childMeals = Integer.parseInt(code.substring(7, 8));
// Get the next four characters separated by a period (the child price)
double childPrice = Double.parseDouble(code.substring(8, 10) + "." + code.substring(10, 12));
/*
* To calculate the subtotal, multiple the adult price by the number of adult
* meals, and the child price by the number of child meals, then add the two
* together.
*/
double subtotal = (price * adultMeals) + (childPrice * childMeals);
// The discount is 15% of the subtotal
double discount = subtotal * 0.15;
// Subtract the discount to get the total
double total = subtotal - discount;
String name = code.substring(12);
System.out.println("Name: " + name);
System.out.println("Adult meals: " + adultMeals);
System.out.println("Child meals: " + childMeals);
System.out.println("Subtotal: " + subtotal);
System.out.println("15% Discount: " + discount);
System.out.println("Total: " + total);
What I would suggest is to read the meal code as a String, then use substring method in order to cut it up in sections. This will work as long as your meal codes follow the same scheme. You will end up with small strings that you can parse as integers or doubles. There are a few ways to handle the lack of decimal points in the prices, like dividing by the amount of precision you want (100 for 2 decimals).
The adult meal part would look something like this:
int numAdultMeals = Integer.parseInt(orderCode.substring(0, 2));
double adultMealPrice = Double.parseDouble(orderCode.substring(2, 6)) / 100.0;
check out javas substring method... you can then divide the input into different variables.
alternatively, store the input to a char array, then grab the items you want from that array using there indexes.
It appears that your input is positional, meaning the first two characters are the quantity, the next four the price, etc.
If that is the case you can use String.substring to divide the string (as in substring(0,2) to get the first two characters). Then use Double.parseDouble() to convert them into numbers (or maybe Integer.parseInt() for the quantities).
You will need to divide the prices by 100 after converting them.

Writing for loops/while loops?

I'm in a programming class in high-school, and I was given an assignment to make a basic subtotal and top calculator, but I work at a restaurant, so it seemed a little pointless to make a calculator that only let you read in one food. So I tried to make it able to take in multiple food items and add them to one price variable. Sorry if some of this code may seem inefficient or redundant. It's only high-school of course.
The issue is, when I run it, it gets up to the asking if there was another food item the user would like to add, and when I type in "Yes" or "No", the program does nothing. Keeps running, but goes no further. Any explanations?
import java.text.NumberFormat;
import java.util.Scanner;
public class Price {
/**
* #param args
*/
public static void main(String[] args) {
final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;
System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes"));
}
System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();
subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;
//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();
System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));
}
}
You have an infinite loop here:
while (done.equalsIgnoreCase("Yes"));
Once you enter Yes, it will keep sitting there and doing nothing because the value of done is Yes and never changes.
Also your loop structure is a bit odd. Your outer for loop runs as many times as the quantity of the first item. But shouldn't you only be multiplying that number to the cost? Because you are either running the loop for as long as the number of items the user entered (by asking them up front) or you don't ask them the total number of items and simply ask them to enter Yes if they want to add more items; you can't really do both.
Your loop should probably look something like this:
String input = "Yes";
while(input.equalsIgnoreCase("Yes")) {
System.out.println ("How many of the first item did you get? ");
quantity1 = kb.nextInt();
System.out.println ("What was the price of that single item? ");
unitPrice1 = kb.nextDouble();
//total += unitPrice1 * quantity1 - you don't have this in your code, but this is where you would be calculating the running total
System.out.println("Was there another food item you'd like to add? ");
input = kb.next();
}
you need to exit for loop when user enters yes, so you can use label here like below:
outerloop:
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes")){
break outerloop;
}
}
Your current code does not do anything inside the while loop if you don't enter yes. And if you enter yes it will be stuck in infinite loop because of your while loop. This is not the efficeint way of looping, but this code will have least change in your current code.
You're while loop is doing nothing, you had given it a condition, but it has no instruction.
Try something like this..(sorry for my rusty java)
'public static void main(String[] args) {
//variable declaration
bool running = true
final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;
while(running = true){
System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
if(done.equalsIgnoreCase("No")){
running = false
//Allows you to break out of the while loop if the user does not want to add anything else
//DO NOT USE BREAK STATMENTS, IT IS A POOR PROGRAMMING PRACTICE.
};//end if
}//end for
}//end while
System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();
//You should comment whats going on here
subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;
//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();
//Output
System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));
}//end main

Output formatting print with two decimal places and commas for place holders

How do you formatt output?
my code is:
package gradplanner;
import java.util.Scanner;
public class GradPlanner {
int cuToComp;
int cuPerTerm;
public static void main(String[] args) {
final double COST = 2890.00; //flat-rate tuition rate charged per term
final int MONPERTERM = 6; //number of months per term
int cuToCompTotal = 0;
int numTerm;
int numMonToComp;
double tuition;
//prompt for user to input the number of CUs for each individual course remaining.
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
int cuToComp = in.nextInt();
//add all CUs from individual courses to find the Total number of CUs left to complete.
while (cuToComp > 0)
{
cuToCompTotal += cuToComp;
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
cuToComp = in.nextInt();
}
System.out.println("The total number of CUs left is " + cuToCompTotal);
//prompt for user to input how many CUs they plan to take per term.
System.out.print("How many credit units do you intend to take per term? ");
int cuPerTerm = in.nextInt();
if (cuPerTerm < 12) //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term
{
System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");
while(cuPerTerm < 12){
System.out.print("How many credit units do you intend to take per term? ");
cuPerTerm = in.nextInt();
}
}
//Calculate the number of terms remaining, if a remain is present increase number of terms by 1.
numTerm = cuToCompTotal/cuPerTerm;
if (cuToCompTotal%cuPerTerm > 0)
{
numTerm = numTerm + 1;
}
System.out.println("The Number of Terms you have left is " + numTerm + " Terms. ");
//Calculate the number of Months left to complete
numMonToComp = numTerm * MONPERTERM;
System.out.println("Which is " + numMonToComp + " Months. ");
//calculate the tuition cost based on the number of terms left to complete.
tuition = numTerm * COST;
System.out.println("Your Total Tuition Cost is: " + "$" + tuition +" . ");
}
}
the final line System.out.println("Your Total Tuition Cost is: " + "$" + tuition +" . ");
I need to format it so that it has two decimal places (amount.00) as well as commas for place holders.
I've tried
System.out.printf("Your Total Tuition Cost is: " + "$%.2f" + tuition +" . ");
however I get an error!!!!
so I added
NumberFormat my = NumberFormat.getInstance(Locale.US);
my.setMaximumFractionDigits(2);
my.setMinimumFractionDigits(2);
String str = my.format(tuition);
System.out.printf("Your Total Tuition Cost is: $", (NumberFormat.getInstance(Locale.US).format(tuition)));
which outputs
Your Total Tuition Cost is: $BUILD SUCCESSFUL (total time: 13 seconds)
What is my mistake???
also there will never be a decimal value the xx.00 will always be .00 (does that matter?)
The best alternative is to use the NumberFormat class, which is better when you want to customize things like decimal separators and placeholders.
Since the output you seem to be looking for is the US standard, you can simply use this:
NumberFormat my = NumberFormat.getInstance(Locale.US);
my.setMaximumFractionDigits(2);
my.setMinimumFractionDigits(2);
String str = my.format(123456.1234);
Another alternative that could be used if it weren't for your placeholder-requirement is to use String.format-method.
An easy way in many cases is to use the String.format method, this line will output like 123456.12
String.format("Your total cost is : $%.02f", tuition);
For some reason, none of the answers here have mentioned currency formatting:
System.out.println("Your Total Tuition Cost is: " +
NumberFormat.getCurrencyInstance().format(tuition));
You can also do the same thing with MessageFormat, which you might or might not find easier to use:
System.out.println(
MessageFormat.format("Your Total Tuition Cost is: {0,number,currency}",
tuition));

Name/variable input and listing

I'm trying to create a program that allows the user to say, input (orange/apple/banana/etc), then the quantity they want to purchase, and the program will calculate the total. However, after trying Strings (Can't multiply them) and a few other options, I'm stuck. I've intensively browsed this forum along with countless guides, to no avail.
The IF statement I inserted was simply a last ditch random attempt to make it work, of course, it crashed and burned. This is all basic stuff I'm sure, but I'm quite new to this.
I would also like to display a list to choose from, perhaps something like
Oranges: Qnty: (Box here)
Apples: Qnty: (Box here)
Bananas: Qnty: (Box here)
Etc
But I'd really settle for help as how to allow the user to input a word, orange, and it is assigned the value I have preset so I can multiply it by the quantity.
All help is appreciated, criticism too of course, to you know, a reasonable extent...
Here's my code.
/* Name 1, x0000
* Name 2, x0001
* Name 3, x0003
*/
import java.util.Scanner;
public class SD_CA_W3_TEST1
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
double nameOfItem1, nameOfItem2, nameofItem3;
double quantityItem1, quantityItem2, quantityItem3;
final double apple = 0.30;
final double orange = 0.45;
final double strawberry = 2.30;
final double potato = 3.25;
final double turnip = 0.70;
final double carrot = 1.25;
double totalCost;
String strNameOfItem1;
System.out.println(" \t \t What would you like to buy today?");
System.out.print("Please choose from our fine selection of: oranges, strawberries, potatoes, turnips, and carrots. \n" );
System.out.print("Enter name of product ");
nameOfItem1 = in.nextDouble();
nameOfItem1 = If = nameOfItem1 (apple, orange, strawberry, potato, turnip, carrot);
System.out.print("Please enter a quantity to purchase");
quantityItem1 = in.nextDouble();
totalCost = quantityItem1 * strNameOfItem1;
System.out.print("The total cost of your purchase is: " +totalCost );
}
}
I would use a HashMap. Here's a good tutorial:
http://www.tutorialspoint.com/java/util/hashmap_get.htm
HashMap food = new HashMap();
food.put("Apple", 0.30);
food.put("Orange", 0.45);
...
then use
food.get("Apple");
to give you the price.
the grand total would be something like:
double quantity = 4.0;
double total = food.get("apple") * quantity;
Try using enums,
class Test{
public enum Fruits{
apple(0.30), orange(0.45), strawberry(2.30), potato(3.25);
private final double value;
Fruits(double value1){
value = value1;
}
public double getValue(){
return value;
}
}
public static void main(String[] args) {
int quantity = 0;
// Read your value here and assign it to quantity
System.out.println(Fruits.apple.getValue()*quantity);
}
}
Enum seems to be a good choice here. It would help you map your item names to the price easily instead of creating several double variables.
private enum Items {
APPLE(0.30), ORANGE(0.45), STRAWBERRY(2.30),
POTATO(3.25), TURNIP(0.70), CARROT(1.25);
double price;
Items(double price) {
this.price = price;
}
double getPrice() {
return price;
}
}
Use Scanner#next() to read in String and use Enum.valueOf() to validate and convert user input into one of your Items.
Scanner in = new Scanner(System.in);
System.out.println("What would you like to buy today?");
System.out.println("Please choose from our fine selection of: " +
"Orange, Strawberry, Potato, Turnip, and Carrot.");
System.out.print("Enter name of product: ");
String nameOfItem = in.next();
Items item;
try {
// Validate Item
item = Items.valueOf(nameOfItem.toUpperCase());
} catch (Exception e) {
System.err.println("No such item exists in catalog. Exiting..");
return;
}
System.out.print("Please enter a quantity to purchase: ");
int quantity;
try {
quantity = in.nextInt();
if (!(quantity > 0)) { // Validate quantity
throw new Exception();
}
} catch (Exception e) {
System.err.println("Invalid quantity specified. Exiting..");
return;
}
double totalCost = quantity * item.getPrice();
System.out.printf("The total cost of your purchase is: %.2f", totalCost);
Output :
What would you like to buy today?
Please choose from our fine selection of: Orange, Strawberry, Potato, Turnip, and Carrot.
Enter name of product: Strawberry
Please enter a quantity to purchase:3
The total cost of your purchase is: 6.90

Using scanner methods for simple Calculation in Java

I'm trying to create a simple program that asks the user to input three items, their quantities, and prices. The program must allow the item names to have spaces. Here is my code that I have written so far.
import java.util.Scanner;
public class AssignmentOne {
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
// System.out.printf("$%4.2f for each %s ", price, item);
// System.out.printf("\nThe total is: $%4.2f ", total);
//process for item one
System.out.println("Please enter in your first item");
String item = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity = kb.nextInt();
System.out.println("Please enter in the price of your item");
double price = kb.nextDouble();
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
System.out.println("\nPlease enter the quantity for this item");
int quantity2 = kb.nextInt();
System.out.print("\nPlease enter in the price of your item");
double price2 = kb.nextDouble();
double total2 = quantity2*price2;
// System.out.printf("$%4.2f for each %s ", price2, item2);
// System.out.printf("\nThe total is: $%4.2f ", total2);
//process for item three
System.out.println("\nPlease enter in your third item");
String item3 = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity3 = kb.nextInt();
System.out.println("Please enter in the price of your item");
double price3 = kb.nextDouble();
double total3 = quantity3*price3;
// System.out.printf("$%4.2f for each %s ", price3, item3);
// System.out.printf("\nThe total is: $%4.2f ", total3);
double total = quantity*price;
double grandTotal = total + total2 + total3;
double salesTax = grandTotal*(.0625);
double grandTotalTaxed = grandTotal + salesTax;
String amount = "Quantity";
String amount1 = "Price";
String amount2 = "Total";
String taxSign = "%";
System.out.printf("\nYour bill: ");
System.out.printf("\n\nItem");
System.out.printf("%30s", amount);
// System.out.printf("\n%s %25d %16.2f %11.2f", item, quantity, price, total);
// System.out.printf("\n%s %25d %16.2f %11.2f", item2,quantity2, price2, total2);
// System.out.printf("\n%s %25d %16.2f %11.2f", item3,quantity3, price3, total3);
System.out.printf("\n%30s", item);
System.out.printf("%30d", quantity);
System.out.printf("\n%30s", item2);
System.out.printf("\n%30s", item3);
System.out.printf("\n\n\nSubtotal %47.2f", grandTotal);
System.out.printf("\n6.25 %s sales tax %39.2f", taxSign, salesTax);
System.out.printf("\nTotal %50.2f", grandTotalTaxed);
}
}
My problem is that when I'm using String item = kb.nextLine(); here's an example of this process when entering the items
Please enter in your first item
soda
Please enter the quantity for this item
10
Please enter the price for this item
15
Please enter in your second item
Please enter the quantity for this item
At this point the first item is fine, but then it comes to the second item and it automatically inputs the second item line and moves straight onto the quantity, I don't understand how to fix this problem and I need to use nextLine(); so the item names can have spaces. Please help.
Try this code
import java.util.Scanner;
class AssignmentOne {
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
// System.out.printf("$%4.2f for each %s ", price, item);
// System.out.printf("\nThe total is: $%4.2f ", total);
//process for item one
System.out.println("Please enter in your first item");
String item = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity = Integer.parseInt(kb.nextLine());
System.out.println("Please enter in the price of your item");
double price = Double.parseDouble(kb.nextLine());
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
System.out.println("\nPlease enter the quantity for this item");
int quantity2 = Integer.parseInt(kb.nextLine());
System.out.print("\nPlease enter in the price of your item");
double price2 =Double.parseDouble( kb.nextLine());
double total2 = quantity2*price2;
// System.out.printf("$%4.2f for each %s ", price2, item2);
// System.out.printf("\nThe total is: $%4.2f ", total2);
//process for item three
System.out.println("\nPlease enter in your third item");
String item3 = kb.nextLine();
System.out.println("Please enter the quantity for this item");
int quantity3 = Integer.parseInt(kb.nextLine());
System.out.println("Please enter in the price of your item");
double price3 = Double.parseDouble(kb.nextLine());
double total3 = quantity3*price3;
// System.out.printf("$%4.2f for each %s ", price3, item3);
// System.out.printf("\nThe total is: $%4.2f ", total3);
double total = quantity*price;
double grandTotal = total + total2 + total3;
double salesTax = grandTotal*(.0625);
double grandTotalTaxed = grandTotal + salesTax;
String amount = "Quantity";
String amount1 = "Price";
String amount2 = "Total";
String taxSign = "%";
System.out.printf("\nYour bill: ");
System.out.printf("\n\nItem");
System.out.printf("%30s", amount);
// System.out.printf("\n%s %25d %16.2f %11.2f", item, quantity, price, total);
// System.out.printf("\n%s %25d %16.2f %11.2f", item2,quantity2, price2, total2);
// System.out.printf("\n%s %25d %16.2f %11.2f", item3,quantity3, price3, total3);
System.out.printf("\n%30s", item);
System.out.printf("%30d", quantity);
System.out.printf("\n%30s", item2);
System.out.printf("\n%30s", item3);
System.out.printf("\n\n\nSubtotal %47.2f", grandTotal);
System.out.printf("\n6.25 %s sales tax %39.2f", taxSign, salesTax);
System.out.printf("\nTotal %50.2f", grandTotalTaxed);
}
}
Because you are using System.in, nothing is sent to the scanner until you've hit "enter". Meaning if you type "15" without hitting "enter", the kb.nextDouble(); call blocks. When you hit "enter" then kb.nextDouble(); reads "15", but there's still a newline in the scanner's buffer. That means this part of the code:
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
Instantly reads the newline that was in the buffer from you typing "15" then hitting "enter". So it won't attempt to read an item name.
You can either replace all of your item name scanning from:
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.nextLine();
to:
//process for item two
System.out.println("\nPlease enter in your second item");
String item2 = kb.next();
Or read the newline and parse the double when you scan for the price:
System.out.println("Please enter in the price of your item");
double price = Double.parseDouble(kb.nextLine());
kb.nextDouble();
I need to check, but it looks likely that nextDouble leaves the newline intact which then is inputed by the consequent `nextLine.
You can solve this problem in two different ways:
Replace .nextLine() with .next() in your code. (But doing this will not allow you to have spaces in the string.
When you read a primitive and then you read a text, add another .nextLine(); after it.
Using the second method in your case you'll have:
System.out.println("Please enter in the price of your item");
double price = kb.nextDouble();
String item2 = kb.nextLine(); // -------------> Added this line also here
//process for item two
System.out.println("\nPlease enter in your second item");
item2 = kb.nextLine();
Which will fix the first problem you have. Make the same for all other places, and your program will run as it supposed to.
Either Use different Scanner Objects for getting String and Numbers. This solves your problem.

Categories

Resources