How do I delimit 2 words with "#" symbol? - java

I have a task from my university where I should prompt the user for 2 numbers one integer the other decimal and print their product in money format. The program should also take in two words delimited by # symbol. I'm struggling to figure out the last portion of the task (two words delimited by # symbol).
Everything else I understand fine.
This is the exercise
Sample run 1:
Enter a whole number: 4
Enter a decimal number: 6.854
Enter two words delimitated by # symbol: Mango#15
Output:
The product of the 2 numbers: 27.416
The product in money format is: N$ 27.42
Assuming the user bought 4 Mango(s) costing N$ 6.85
The VAT to be charged is 15%, hence total due to be paid is N$ 31.53
This is my code.
import java.util.Scanner;
public class Lab02_Task4 {
public static void main(String[]args){
Scanner info = new Scanner(System.in);
int whole;
System.out.println("Enter a whole number: ");
whole = info.nextInt();
double decimal;
System.out.println("Enter a decimal number: ");
decimal = info.nextDouble();
String item;
System.out.println("Enter two words delimitated by # symbol: ");
item = info.nextLine();
String item2 = "Mango";
double total = whole * decimal;
double vatIncluded = (total * 0.15) + total;
String s=String.valueOf(total);
System.out.println("The product of the 2 numbers: " + total);
String total2 = String.format("%.2f", total);
System.out.println("The product in money format is: N$ " + (total2));
String vatIncluded2 = String.format("%.2f", vatIncluded);
System.out.println("Assuming the user bought " + whole + " " + item2 + "(s) " + "costing N$ " + total2 +
" The VAT to be charged is 15%, hence total due to be paid is N$ " + vatIncluded2);
}
}

You can use split to separate the two values like this:
public static void main(String[] args) {
String string = "value#anothervalue";
String[] arr = string.split("#");
System.out.print(Arrays.toString(arr)); //[value, anothervalue]
}

This will do the trick:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int wholenumber = Integer.parseInt(input.nextLine());
double decimal = Double.parseDouble(input.nextLine());
String[] deli = input.nextLine().split("#");
String item = deli[0];
int tax = Integer.parseInt(deli[1]);
double product = decimal*wholenumber;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String rounded = formatter.format(product).substring(1);
double finalprice = product*tax/100+product;
System.out.println("The product of the 2 numbers: "+product);
System.out.println("The product in money format is: N$"+rounded);
System.out.println("Assuming the user bought "+wholenumber+" "+item+"s costing N$"+formatter.format(decimal).substring(1));
System.out.println("The VAT to4 be charged is "+tax+"%, hence the total due to the paid is N$"+finalprice);
//The VAT to be charged is 15%, hence total due to be paid is N$ 31.53
}
Sample Run
4
6.854
Mango#15
The product of the 2 numbers: 27.416
The product in money format is: N$27.42
Assuming the user bought 4 Mangos costing N$6.85
The VAT to4 be charged is 15%, hence the total due to the paid is N$31.5284
With user prompts
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int wholenumber = Integer.parseInt(input.nextLine());
System.out.print("Enter a decimal number: ");
double decimal = Double.parseDouble(input.nextLine());
System.out.print("Enter two words seperated by # symbol: ");
String[] deli = input.nextLine().split("#");
String item = deli[0];
int tax = Integer.parseInt(deli[1]);
double product = decimal*wholenumber;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String rounded = formatter.format(product).substring(1);
double finalprice = product*tax/100+product;
System.out.println("The product of the 2 numbers: "+product);
System.out.println("The product in money format is: N$"+rounded);
System.out.println("Assuming the user bought "+wholenumber+" "+item+"s costing N$"+formatter.format(decimal).substring(1));
System.out.println("The VAT to4 be charged is "+tax+"%, hence the total due to the paid is N$"+finalprice);
//The VAT to be charged is 15%, hence total due to be paid is N$ 31.53
}
Sample Run
Enter a number: 4
Enter a decimal number: 6.854
Enter two words seperated by # symbol: Mango#15
The product of the 2 numbers: 27.416
The product in money format is: N$27.42
Assuming the user bought 4 Mangos costing N$6.85
The VAT to4 be charged is 15%, hence the total due to the paid is N$31.5284

Related

The operator * is undefined for the argument type(s) int, String / Type mismatch: cannot convert from double to int

import java.util.Scanner;
public class Asgn1 {
//comment practice
/*multi-line comment practice
* no text fill
*/
public static void main(String[] args) {
//user prompted inputs for future calculations
Scanner in = new Scanner(System.in);
System.out.println("The following information is required:");
System.out.println("Enter customer ID: ");
String customerId = in.nextLine();
System.out.println("Enter unit price in decimal format (up to two decimals, e.g. 3.5): ");
String unitPrice = in.nextLine();
System.out.println("Enter quantity (whole numbers only): ");
String orderQuantity = in.nextLine();
System.out.println("Enter product description, (e.g. 'whole wheat bread'): ");
String productDescription = in.nextLine();
System.out.println("Enter discount in decimal format (e.g. .05 = 5%): ");
String appliedDiscount = in.nextLine();
//confirm order data details and display to user
System.out.println("Your order data is as follows: ");
System.out.println("Customer ID: " + customerId);
System.out.println("Unit Price: " + unitPrice);
System.out.println("Order Quantity: " + orderQuantity );
System.out.println("Product Description: " + productDescription);
System.out.println("Applied Discount: " + appliedDiscount);
//calculation formulas based on users input
int beforeDiscount = (Integer.parseInt(unitPrice) * Integer.parseInt(orderQuantity));
int afterDiscount = 1 - (Integer.parseInt(unitPrice) * Integer.parseInt(orderQuantity)) * (appliedDiscount);
//totals before and after discount
System.out.println("Your Order Totals");
System.out.println("Before Discount: ");
System.out.println("After Discount: ");
}
}
I have this java code I want to take the unit price and multiply that by the order quantity, then apply the discount so I can display a before and after discount price.
Originally, when I entered this, I figured out I had to parse the strings for unitPrice and orderQuantity as ints, but when I tried that with the double, I got this message as well on the same line: "Type mismatch: cannot convert from double to int".
I tried looking around at other answers but could not find something that would fix this issue so I'm asking for help, please. What would be the best way to solve this?
In the future, should I try to alter it before it comes in, maybe where they input it, or do I wait until I get the values and then alter that? What would convention dictate?
Thank you for your consideration and assistance.
I change some things on the code... first, the type of variables of unit price and appliedDiscount into double. And also I change the formula to calculate price after discount.
public static void main(String[] args) {
//user prompted inputs for future calculations
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
System.out.println("The following information is required:");
System.out.println("Enter customer ID: ");
String customerId = in.nextLine();
System.out.println("Enter unit price in decimal format (up to two decimals, e.g. 3.5): ");
double unitPrice = in.nextDouble();
System.out.println("Enter quantity (whole numbers only): ");
int orderQuantity = in.nextInt();
System.out.println("Enter product description, (e.g. 'whole wheat bread'): ");
String productDescription = in2.nextLine();
System.out.println("Enter discount in decimal format (e.g. .05 = 5%): ");
double appliedDiscount = in.nextDouble();
//confirm order data details and display to user
System.out.println("Your order data is as follows: ");
System.out.println("Customer ID: " + customerId);
System.out.println("Unit Price: " + unitPrice);
System.out.println("Order Quantity: " + orderQuantity );
System.out.println("Product Description: " + productDescription);
System.out.println("Applied Discount: " + appliedDiscount);
//calculation formulas based on users input
double beforeDiscount = (unitPrice * orderQuantity);
double afterDiscount = beforeDiscount - (beforeDiscount * (appliedDiscount));
//totals before and after discount
System.out.println("Your Order Totals" );
System.out.println("Before Discount: "+ beforeDiscount);
System.out.println("After Discount: " + afterDiscount);
}

Hello I can't seem to figure out why my program isn't working

The program is to calculate the total price for meat but I keep getting the output of $.68 instead of $10.89, any help would be greatly appreciated. While i'm sure it's most likely a error with the last println statement any help would be useful.
/**********************************************************************
Program: Deli.java
Description: Computes the price of a deli item given the weight (in ounces)
and the price per pound.
***********************************************************************/
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Deli
{
/* -------------------------------------------------------------------------------------
The function main reads in the price per pound of a deli item
and the number of ounces of a deli item then computes the total price
and prints a "label" for the item that includes the unit price (per pound),
the weight and total price.
----------------------------------------------------------------------------------------*/
public static void main (String[] args)
{
final double OUNCES_PER_POUND = 16.0;
double pricePerPound; // price per pound
double weightOunces; // weight in ounces
double weight; // weight in pounds
double totalPrice; // total price for the item
Scanner scan = new Scanner(System.in);
/* ------------------------------------------------------------------------
Declare money as a NumberFormat object and use the
getCurrencyInstance method to assign it a value.
Declare fmt as a DecimalFormat object and instantiate
it to format numbers with at least one digit to the left of the
decimal and the fractional part rounded to two digits.
Prompt the user and read in each input.
-------------------------------------------------------------------------*/
NumberFormat format1 = NumberFormat.getCurrencyInstance();
DecimalFormat format2 = new DecimalFormat("0.##");
System. out. println ("Welcome to the CS Deli! ! \n ");
System.out.print ("Enter the price per pound of your item: ");
pricePerPound = scan.nextDouble();
System.out.print ("Enter the weight (ounces): ");
weightOunces = scan.nextDouble();
// Convert ounces to pounds and compute the total price
weight = weightOunces / OUNCES_PER_POUND;
totalPrice = pricePerPound * weight;
// Print the unit price, weight, and total price using the formatting objects.
// Format the weight in pounds and use the money format for the prices.
System.out.println("\nUnit Price: " + format1.format(pricePerPound) + " per pound");
System.out.println("\nWeight: " + format2.format(weightOunces) + " pounds");
System.out.println("\nTotal Price: " + format1.format(totalPrice));
}
}
"The inputs are $4.25 for the unit price, and 2.56 pounds."
I think you're a little confused here as to how your application is expecting its input. The prompts ask for The price per pound:
Enter the price per pound of your item: 4.25
and then asks to enter The weight in ounces:
Enter the weight (ounces): 2.56
Again, it asks to enter in ounces not pounds. The code then takes this ounces input (2.56) and converts it to pounds which ends up being about 0.16 pounds. Well, I suppose 0.16 pounds of the item which is priced at $4.25 per pound will cost you $0.68 dollars (or just 68 cents).
If you really wanted to purchase 2.56 pounds of the item then you should have supplied 40.96 (2.56 * 16) in the ounces prompt.
As #JohnBayko has already so graciously pointed out, you are displaying the wrong value in your output from this code line:
System.out.println("\nWeight: " + format2.format(weightOunces) + " pounds");
It should be your conversion value displayed not what was entered:
System.out.println("\nWeight: " + format2.format(weight) + " pounds");

How do I format printing a integer so that all the places to the left of the decimal line up?

This program runs fine the issue is a formatting one when "System.out.print("Tax: $%.2f\n", tax);" line runs. The issue is that I need to output to line up with the other outputs. I've tried simply using space, but then when it's any bigger than three places to the left of the decimal it no longer lines up.
This image shows what my output is.
This image shows what my output should be.
import java.util.Scanner;
import java.time.LocalDate;
import java.time.Period;
/**
*Program generates pay stub for employee.
*Details several variables.
* #author Taylor Schaefer ts1178
* #version 19
*/
public class PayStub {
/**
* #param args insert description here
*/
public static void main(String[] args) {
//Install scanner and declare all variable
Scanner keyboard = new Scanner(System.in);
//Inputting name
System.out.print("Enter your Fullname: ");
String fullName = keyboard.nextLine();
//Inputting anniversary month
System.out.print("Enter your Anniversary Month(1-12): ");
int month = keyboard.nextInt();
//Inputting anniversary year
System.out.print("Enter your Anniversary Year: ");
int year = keyboard.nextInt();
//Hours per week worked
System.out.print("Enter your hours worked this pay period(0-350): ");
int hours = keyboard.nextInt();
//Inputting name
System.out.print("Enter your Job Title: ");
String blank = keyboard.nextLine();
String jobTitle = keyboard.nextLine();
//Hourly pay rate
System.out.print("Enter your pay rate:");
double rate = keyboard.nextDouble();
//current pay month 9
//current pay year 2018
int day = 1;
LocalDate start = LocalDate.of(year, month, day);
LocalDate today = LocalDate.of(2018, 9, 1);
//calculate the time that has passed
Period age = Period.between(start, today);
int years = age.getYears();
int months = age.getMonths();
//Print total number of months worked and declare variable total months
int totalMonths = months + years * 12;
//Declare Variable vacation Hours
double vacation = totalMonths * 8.25;
//Declare and define gross pay
double grossPay = hours * rate;
//Declare and calculate retirement
double retirement = grossPay * .052;
//Declare and calculate tax withholding
double tax = (grossPay - retirement) * .28;
//Declare and calculate net pay
double netPay = grossPay - (tax + retirement);
//Print Payroll
//
System.out.println();
System.out.println();
System.out.println("==========================================");
//Company Name
System.out.println(" Gekko & Co.");
System.out.println();
//Print Logo
System.out.println(" \"$\"");
System.out.println(" ~~~");
System.out.println(" / \\ `.");
System.out.println(" / \\ /");
System.out.println(" /_ _ _ \\/");
System.out.println(); //divider
//Single Line Divider
System.out.println("------------------------------------------");
//Print Pay Period
System.out.println("Pay Period: 9/2018");
//Print Name
System.out.println("Name: " + fullName);
//Print Title
System.out.println("Title: " + jobTitle);
//Print anniversary month and year
System.out.println("Anniversary: " + month + "/" + year);
//Print months worked
System.out.println("Months Worked: " + totalMonths + " months");
//Print vacation hours earned
System.out.printf("Vacation hours: %.2f\n", vacation);
//Single Line Divider
System.out.println("------------------------------------------");
//Print Gross Pay
System.out.printf("Gross Pay: $%.2f\n", grossPay);
//Print Retirement Amount
System.out.printf("Retirement: $ %.2f\n", retirement);
//Print Tax withholding amount
System.out.printf("Tax: $%.2f\n", tax);
//Single Line Divider
System.out.println("------------------------");
//Print Net Pay
System.out.printf("Net Pay: $%.2f\n", netPay);
//Print Footer
System.out.println("==========================================");
}
}
Use the width specifier - which includes the decimal point and precision so for a value like 815.74 to line up with a value like 3073.18 use $%7.2f.
System.out.printf("abc $%7.2f%n", 815.74);
System.out.printf("abc $%7.2f%n", 3073.18);
prints
abc $ 815.74
abc $3073.18
Of course if you can't assume the maximum number of digits then you'd compute the max digits - and while we're at it throw in some commas (and account for them for width) (aka comma grouping separator):
// here you'd compute the max value of all the numbers your printing
double maxValue = 1721890.23;
int maxDigits = ((int)Math.log10(maxValue) + 1);
int numCommas = (maxDigits-1) / 3;
int precision = 2;
int precDecimalPt = (precision + 1);
int totalWidth = (maxDigits+precDecimalPt+numCommas);
String formatStr = "$%,"+totalWidth+"."+precision+"f%n";
System.out.printf("Gross Pay: "+formatStr, 815.74);
System.out.printf("Retirement: "+formatStr, 3073.18);
System.out.printf("Tax: "+formatStr, maxValue);
prints:
Gross Pay: $ 815.74
Retirement: $ 3,073.18
Tax: $1,721,890.23
Then let's say you had a bunch of prefix text of varying length and didn't want to account for spaces for padding but wanted all the text to line up and be aligned to the left...then format that too with a width specifier and a left-justified flag:
// replaces portion of above...
String formatStr = "%-30s$%,"+totalWidth+"."+precision+"f%n";
System.out.printf(formatStr, "Gross Pay:", 815.74);
System.out.printf(formatStr, "Retirement:", 3073.18);
System.out.printf(formatStr, "Tax:", maxValue);
prints
Gross Pay: $ 815.74
Retirement: $ 3,073.18
Tax: $1,721,890.23
Other considerations to account for:
can a value ever be negative and displayed as such
what happens when prefix is larger than accounted for

I am stuck on homework assignment Commission Calculation

I need to compare the total annual sales of at least three people. I need my app to calculate the additional amount that each must achieve to match or exceed the highest earner. I figured out most of it and know how to do it if there were only two people in the scenario, but getting third into the equation is throwing me for a loop! Any help is appreciated and thanks in advance! Here's what I have so far, but obviously at the end where the calculations are not going to be right.
package Commission3;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
// Create a new object AnnualCompensation
Commission3 salesPerson[] = new Commission3[2];
// creat two object
salesPerson[0] = new Commission3();
salesPerson[1] = new Commission3();
salesPerson[2] = new Commission3();
//new scanner input
Scanner keyboard = new Scanner(System.in);
//get salesperson1 name
System.out.println("What is your first salesperson's name?");
salesPerson[0].name = keyboard.nextLine();
//get salesperson1 sales total
System.out.println("Enter annual sales of first salesperson: ");
double val = keyboard.nextDouble();
salesPerson[0].setAnnualSales(val);
//get salesperson2 name
System.out.println("What is your second salesperson's name?");
salesPerson[1].name = keyboard.next();
//get salesperson2 sales total
System.out.println("Enter annual sales of second salesperson: ");
val = keyboard.nextDouble();
salesPerson[1].setAnnualSales(val);
//get salesperson3 name
System.out.println("What is your third salesperson's name?");
salesPerson[2].name = keyboard.next();
//get salesperson3 sales total
System.out.println("Enter annual sales of third salesperson: ");
val = keyboard.nextDouble();
salesPerson[2].setAnnualSales(val);
double total1, total2, total3;
total1 = salesPerson[0].getTotalSales();
System.out.println("Total sales of " + salesPerson[0].name +" is: $" + total1);
total2 = salesPerson[1].getTotalSales();
System.out.println("Total sales of " + salesPerson[1].name +" is: $" + total2);
total3 = salesPerson[2].getTotalSales();
System.out.println("Total sales of " + salesPerson[2].name +" is: $" + total3);
if (total1 > total2) {
System.out.print("Salesperson " + salesPerson[2].name + "'s additional amount
of sales that he must " + " achieve to match or exceed the higher of the
salesperson " + salesPerson[0].name);
System.out.println(" $" + (total1 - total2));
} else if (total2 > total1) {
System.out.print("Salesperson " + salesPerson[0].name + "'s additional amount
of sales that he must " + " achieve to match or exceed the higher of the
salesperson " + salesPerson[1].name);
System.out.println(" $" + (total2 - total1));
} else {
System.out.println("Both have same compensation $" + total1);
}
}
}
When you take the input from the user, keep track of the highest sales thus far, and the name of the salesperson with the most sales.
Then, instead of checking total1 and total2, you can loop through all three, and compare them to the max. If the current total is less than the max, then calculate the difference. Otherwise, the current total is equal to the max, and you don't need to do the calculation.
I'll leave the actual code for you to figure out.

How to use formatting with printf correctly in Java

I'm trying to create a simple program to take in three items, their quantities, and prices and added them all together to create a simple receipt type format. My professor gave me a specific format for the receipt where all the decimals line up and are consistently placed. It should look like this.
Your Bill:
Item Quantity Price Total
Diet Soda 10 1.25 12.50
Candy 1 1.00 1.00
Cheese 2 2.00 4.00
Subtotal 17.50
6.25% Sales Tax 1.09
Total 18.59
My professor specified there should be 30 characters for the name, 10 for quantity and price and total. Doing this I have to use the printf method. I'm trying to format it with this code so far.
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("%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%s", item);
System.out.printf("%30d", quantity);
System.out.printf("\n%s", item2);
System.out.printf("\n%s", 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);
}
}
If I enter in a longer item name, it moves the placement of quantity and price and total.
My question is, how do I make a set start point with a limited width using printf, please help.
System.out.printf("%1$-30s %2$10d %3$10.2f %4$10.2f", "Diet Soda", 10, 1.25, 12.50);
Will print the line
Diet Soda 10 1.25 12.50
The first string passed to the printf method is a series of format specifiers that describe how we want the rest of the arguments to be printed. Around the format specifiers you can add other characters that will also be printed (without being formatted).
The format specifiers above have the syntax:
%[index$][flags][width][.precision]conversion where [] denotes optional.
% begins a formatting expression.
[index$] indicates the index of the argument that you want to format. Indices begin at 1. The indices above are not actually needed because each format specifier without an index is assigned one counting up from 1.
[-] The only flag used above, aligns the output to the left.
[width] indicates the minimum number of characters to be printed.
[.precision] In this case the number of digits to be written after the decimal point, although this varies with different conversions.
conversion character(s) indicating how the argument should be formatted. d is for decimal integer, f is decimal format for floating points, s doesn't change the string in our case.
More information can be found here.

Categories