I have been successful in compiling my inventory program:
// Inventory.java part 1
// this program is to calculate the value of the inventory of the Electronics Department's cameras
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Inventory
{
public static void main(String[] args)
{
// create Scanner to obtain input from the command window
Scanner input = new Scanner (System.in);
String name;
int itemNumber; // first number to multiply
int itemStock; // second number to multiply
double itemPrice; //
double totalValue; // product of number1 and number2
while(true){ // infinite loop
// make new Camera object
System.out.print("Enter Department name: "); //prompt
String itemDept = input.nextLine(); // read name from user
if(itemDept.equals("stop")) // exit the loop
break;
{
System.out.print("Enter item name: "); // prompt
name = input.nextLine(); // read first number from user
input.nextLine();
}
System.out.print("Enter the item number: "); // prompt
itemNumber = input.nextInt(); // read first number from user
input.nextLine();
while( itemNumber <= -1){
System.out.print("Enter valid number:"); // prompt
itemNumber = input.nextInt(); // read first number from user input.nextLine();
} /* while statement with the condition that negative numbers are entered
user is prompted to enter a positive number */
System.out.print("Enter number of items on hand: "); // prompt
itemStock = input.nextInt(); // read first number from user
input.nextLine();
while( itemStock <= -1){
System.out.print("Enter positive number of items on hand:"); // prompt
itemStock = input.nextInt(); // read first number from user
input.nextLine();
} /* while statement with the condition that negative numbers are entered
user is prompted to enter a positive number */
System.out.print("Enter item Price: "); // prompt
itemPrice = input.nextDouble(); // read second number from user
input.nextLine();
while( itemPrice <= -1){
System.out.print("Enter positive number for item price:"); // prompt
itemPrice = input.nextDouble(); // read first number from user
input.nextLine();
} /* while statement with the condition that negative numbers are entered
user is prompted to enter a positive number */
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice);
totalValue = itemStock * itemPrice; // multiply numbers
System.out.println("Department name:" + itemDept); // display Department name
System.out.println("Item number: " + camera.getItemNumber()); //display Item number
System.out.println("Product name:" + camera.getName()); // display the item
System.out.println("Quantity: " + camera.getItemStock());
System.out.println("Price per unit" + camera.getItemPrice());
System.out.printf("Total value is: $%.2f\n" + totalValue); // display product
} // end while method
} // end method main
}/* end class Inventory */
class Cam{
private String name;
private int itemNumber;
private int itemStock;
private double itemPrice;
private String deptName;
public Cam(String name, int itemNumber, int itemStock, double itemPrice) {
this.name = name;
this.itemNumber = itemNumber;
this.itemStock = itemStock;
this.itemPrice = itemPrice;
}
public String getName(){
return name;
}
public int getItemNumber(){
return itemNumber;
}
public int getItemStock(){
return itemStock;
}
public double getItemPrice(){
return itemPrice;
}
}
C:\Java>java Inventory
Enter Department name: Electronics
Enter item name: camera
Enter the item number: 12345
Enter number of items on hand: 8
Enter item Price: 100.50
Department name:Electronics
Item number: 12345
Product name:camera
Quantity: 8
Price per unit100.5
Total value is:
$Exception in thread "main" java.util.MissingFormatArgumentException:
Format specifier '.2f'
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at Inventory.main(Inventory.java:82)
I seem to come to this format error and cannot see why.
If you are using printf, you need to specify the placeholders as printf parameters along with the format string. In your case you are passing a single string by appending the amount hence the error.
System.out.printf("Total value is: $%.2f\n" + totalValue)
should be replaced by
System.out.printf("Total value is: $%.2f\n", totalValue)
This is the problem:
System.out.printf("Total value is: $%.2f\n" + totalValue);
I think you meant:
System.out.printf("Total value is: $%.2f\n", totalValue);
In other words, specify the value to replace the placeholder with, instead of just using string concatenation to add the value to the send of the format string.
In general though, when you get an exception you don't understand, you should look at the documentation for it. In this case, the docs are reasonably clear:
Unchecked exception thrown when there is a format specifier which does not have a corresponding argument or if an argument index refers to an argument that does not exist.
So there are two things you need to check in your code:
Do you have a format specifier without a corresponding argument?
Do you have an argument index which refers to an argument that doesn't exist?
You haven't specified any argument indexes in your format string, so it must be the first case - which indeed it is.
System.out.printf("Total value is: $%.2f\n", totalValue); // display product
-> http://www.java2s.com/Code/JavaAPI/java.lang/Systemoutprintf2ffloatf.htm
Related
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);
}
To begin my question, here is my question prompt:
Create a program using classes that does the following in the zyLabs developer below. For this lab, you will be working with two different class files. To switch files, look for where it says "Current File" at the top of the developer window. Click the current file name, then select the file you need.
(1) Create two files to submit:
ItemToPurchase.java - Class definition
ShoppingCartPrinter.java - Contains main() method
Build the ItemToPurchase class with the following specifications:
Private fields
String itemName - Initialized in default constructor to "none"
int itemPrice - Initialized in default constructor to 0
int itemQuantity - Initialized in default constructor to 0
Default constructor
Public member methods (mutators & accessors)
setName() & getName() (2 pts)
setPrice() & getPrice() (2 pts)
setQuantity() & getQuantity() (2 pts)
(2) In main(), prompt the user for two items and create two objects of the ItemToPurchase class. Before prompting for the second item, call scnr.nextLine(); to allow the user to input a new string. (2 pts)
Ex:
Item 1
Enter the item name: Chocolate Chips
Enter the item price: 3
Enter the item quantity: 1
Item 2
Enter the item name: Bottled Water
Enter the item price: 1
Enter the item quantity: 10
(3) Add the costs of the two items together and output the total cost. (2 pts)
Ex:
TOTAL COST
Chocolate Chips 1 # $3 = $3
Bottled Water 10 # $1 = $10
Total: $13
My code:
ItemToPurhase.java
public class ItemToPurchase {
//Private fields - itemName, itemPrice, and itemQuanity
private String itemName = "none";
private int itemPrice = 0;
private int itemQuantity = 0;
/*Default Constructor
itemName - Initialized to "none"
itemPrice - Initialized to 0
itemQuantity - Initialized ito 0
*/
public ItemToPurchase () {
this.itemName = "none";
this.itemPrice = 0;
this.itemQuantity = 0;
}
//public member methods (mutators & accessors)
//setName() & getName()
public void setName (String itemName) {
this.itemName = itemName;
}
public String getName() {
return itemName;
}
//setPrice() & getPrice()
public void setPrice (int itemPrice) {
this.itemPrice = itemPrice;
}
public int getPrice(){
return itemPrice;
}
//setQuantity() & getQuantity()
public void setQuantity (int itemQuantity) {
this.itemQuantity = itemQuantity;
}
public int getQuantity() {
return itemQuantity;
}
//print item to purchase
public void printItemPurchase() {
System.out.println(itemQuantity + " " + itemName + " $" + itemPrice +
" = $" + (itemPrice * itemQuantity));
}
}
ShoppingCartPrinter.java
import java.util.Scanner;
public class ShoppingCartPrinter {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int i = 0;
String productName;
int productPrice = 0;
int productQuantity = 0;
int cartTotal = 0;
ItemToPurchase item1 = new ItemToPurchase();
ItemToPurchase item2 = new ItemToPurchase();
// Get item 1 details from user, create itemToPurchase object
System.out.println("Item 1");
System.out.println("Enter the item name: ");
productName = scnr.next();
item1.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item1.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item1.setQuantity(productQuantity);
System.out.println("");
// Get item 2 details from user, create itemToPurchase object
System.out.println("Item 2");
System.out.println("Enter the item name: ");
productName = scnr.next();
item2.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item2.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item2.setQuantity(productQuantity);
System.out.println("");
// Add costs of two items and print total
cartTotal = (item1.getQuantity() * item1.getPrice()) + (item2.getQuantity() * item2.getPrice());
System.out.println("TOTAL COST");
// cartTotal = item one price + item two price
// Totoal Cost
// item one information
int item1Total = item1.getPrice() * item1.getQuantity();
System.out.println(item1.getName() + " " + item1.getQuantity() + " # $" + item1.getPrice() + " = $" + item1Total);
// item two information
int item2Total = item2.getPrice() * item2.getQuantity();
System.out.println(item2.getName() + " " + item2.getQuantity() + " # $" + item2.getPrice() + " = $" + item2Total);
// Total output
System.out.println("");
System.out.print("Total: $" + cartTotal);
return;
}
}
Although I am getting no errors for most of the submissions, there are 2 submissions that raise the "Exception in thread "main" java.util.InputMismatchException" error.
Example:
Exited with return code 1.
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at ShoppingCartPrinter.main(ShoppingCartPrinter.java:23)
Output differs. See highlights below.
Input:
Chocolate Chips
3
1
Bottled Water
1
10
Your output:
Item 1
Enter the item name:
Enter the item price:
Expected output(!):
Item 1
Enter the item name:
Enter the item price:
Enter the item quantity:
Item 2
Enter the item name:
Enter the item price:
Enter the item quantity:
TOTAL COST
Chocolate Chips 1 # $3 = $3
Bottled Water 10 # $1 = $10
Total: $13
My code seems correct for other inputs that are very similar but for some reason, the compiler that my professor uses keeps prompting this error for a very few cases.
If you have not already done so, I suggest that you read the documentation for class java.util.Scanner.
This line of your code is throwing the InputMismatchException.
productPrice = scnr.nextInt();
That means that scnr read a token that was not an int. This is because your product contained two words, namely Chocolate Chips. So this line of your code only read Chocolate
productName = scnr.next();
and hence method nextInt read Chips which is not an int.
You need to change the code and call method nextLine rather than method next. Again, refer to the documentation to understand why.
Also, after calling method nextInt and before calling method nextLine, you need an extra call to method nextLine. Refer to Scanner is skipping nextLine() after using next() or nextFoo()? to understand why.
Only class ShoppingCartPrinter needs to be changed. Here is the changed code. I have added comments to indicate the changes, namely CHANGE HERE and ADDED THIS LINE.
import java.util.Scanner;
public class ShoppingCartPrinter {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int i = 0;
String productName;
int productPrice = 0;
int productQuantity = 0;
int cartTotal = 0;
ItemToPurchase item1 = new ItemToPurchase();
ItemToPurchase item2 = new ItemToPurchase();
// Get item 1 details from user, create itemToPurchase object
System.out.println("Item 1");
System.out.println("Enter the item name: ");
productName = scnr.nextLine(); // CHANGE HERE
item1.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item1.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item1.setQuantity(productQuantity);
scnr.nextLine(); // ADDED THIS LINE
System.out.println("");
// Get item 2 details from user, create itemToPurchase object
System.out.println("Item 2");
System.out.println("Enter the item name: ");
productName = scnr.nextLine(); // CHANGE HERE
item2.setName(productName);
System.out.println("Enter the item price: ");
productPrice = scnr.nextInt();
item2.setPrice(productPrice);
System.out.println("Enter the item quantity: ");
productQuantity = scnr.nextInt();
item2.setQuantity(productQuantity);
System.out.println("");
// Add costs of two items and print total
cartTotal = (item1.getQuantity() * item1.getPrice())
+ (item2.getQuantity() * item2.getPrice());
System.out.println("TOTAL COST");
// cartTotal = item one price + item two price
// Totoal Cost
// item one information
int item1Total = item1.getPrice() * item1.getQuantity();
System.out.println(item1.getName() + " " + item1.getQuantity() + " # $" + item1.getPrice()
+ " = $" + item1Total);
// item two information
int item2Total = item2.getPrice() * item2.getQuantity();
System.out.println(item2.getName() + " " + item2.getQuantity() + " # $" + item2.getPrice()
+ " = $" + item2Total);
// Total output
System.out.println("");
System.out.print("Total: $" + cartTotal);
return;
}
}
I am trying to make a simple calculator program where a user enters two values, the method add() is called from the Operations class and the values are added and the result is displayed. And then I am using a do while loop in which the user keeps entering values which are added to the last total and the result is displayed. It has to keep running unless the user enters some input which is not of the type double.
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number: ");
double number = input.nextDouble();
System.out.println("Enter the second number: ");
double number2 = input.nextDouble();
double total = Operations.add(number, number2);
System.out.println(total);
System.out.println("Enter the number again: );
number2 = input.nextDouble();
do {
total = Operations.add(total, number2);
System.out.println(total);
System.out.println("Enter the number again: ");
number2 = input.nextDouble();
} while (input.hasNextDouble());
System.out.println("Exit.");
}
}
And here is the Operations class
public class Operations {
public static double add(double n1, double n2) {
return n1 + n2;
}
}
It adds the first two values, and displays the result. Then it asks for the value again, user inputs, and it displays the result. But from here on there is a problem somewhere which I have tried so hard to figure out but couldn't do so. So please look over my code and tell me where the problem is. Its something in the do while loop which I am doing wrong.
Output:
Enter the first number:
5
Enter the second number:
2
7.0
Enter the number again:
1
8.0
Enter the number again please:
2
Here the program is running but does nothing when I press 2. If for example I press 6 again, it will still add 2 (which I entered before) to the total and display that
6
10.0
Enter the number again please:
Your issue lies with the order in which things are occurring. You want to prompt and input at the beginning of the do-while:
do {
System.out.println("Enter the number again: ");
number2 = input.nextDouble();
total = Operations.add(total, number2);
System.out.println(total);
} while (input.hasNextDouble());
This makes the first re-prompt and re-input redundant, so your final class looks like:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number: ");
double number = input.nextDouble();
System.out.println("Enter the second number: ");
double number2 = input.nextDouble();
double total = Operations.add(number, number2);
System.out.println(total);
do {
System.out.println("Enter the number again: ");
number2 = input.nextDouble();
total = Operations.add(total, number2);
System.out.println(total);
} while (input.hasNextDouble());
System.out.println("Exit.");
}
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.
The assignment is:
Write a program that provides 20% discount for member who purchase any two books at XYZ bookstore. (Hint: Use constant variable to the 20% discount.)
I have done the coding, but cannot prompt book name, and then show the discounted price. Please see my coding below and modify it as your needs.
import java.util.Scanner;
public class Book_Discount {
public static void main(String args[]) {
public static final double d = 0.8;
Scanner input = new Scanner(System.in);
int purchases;
double discounted_price;
System.out.print("Enter value of purchases: ");
purchases = input.nextInt();
discounted_price = purchases * d; // Here discount calculation takes place
// Displays discounted price
System.out.println("Value of discounted price: " + discounted_price);
}
}
For prompting the book name as well, you write something like:
/* Promt how many books */
System.out.print("How many books? ");
int bookCount = scanner.nextInt();
scanner.nextLine(); // finish the line...
double totalPrice = 0.0d; // create a counter for the total price
/* Ask for each book the name and price */
for (int i = 0; i < bookCount; ++i)
{
System.out.print("Name of the book? ");
String name = scanner.nextLine(); // get the name
System.out.print("Price of the book? ");
double price = scanner.nextDouble(); // get the price
scanner.nextLine(); // finish the line
totalPrice += price; // add the price to the counter
}
/* If you bought more than 1 book, you get discount */
if (bookCount >= 2)
{
totalPrice *= 0.8d;
}
/* Print the resulting price */
System.out.printf("Total price to pay: %.2f%n", totalPrice);