What causes the "Exception in thread "main" java.util.InputMismatchException" error? - java

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

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

How can I fix my NoSuchElementException?

I've tried many different ways to fix the error. I know it has something to do with the hasNext, I'm just not sure where the error is. Please help. Also if someone could tell me how I can get the value of the variable largestQuantity into the main method from my getLargestQuantityItem method I'd appreciate that. Cheers!
Here is the input file that is a .txt file:
The Shawshank Redemption
100
19.95
DVD
The Dark Knight
50
19.95
DVD
Casablanca
137
9.95
DVD
The Girl With The Dragon Tattoo
150
14.95
Book
Vertigo
55
9.95
DVD
A Game of Thrones
100
8.95
Book
Here is my code:
import java.util.*;
import java.io.*;
public class Project01 {
public static void main(String[] args) {
ArrayList<String> Titles = new ArrayList<String>();
ArrayList<String> Types = new ArrayList<String>();
ArrayList<Double> Prices = new ArrayList<Double>();
ArrayList<Integer> Quantities = new ArrayList<Integer>();
int count = 0;
Scanner in = new Scanner(System.in);
String database = getFile(in);
try {
File file = new File(database);
Scanner inputFile = new Scanner(file);
System.out.println();
System.out.println("Product Summary Report");
System.out.println("------------------------------------------------------------");
while (inputFile.hasNext()) {
getTitle(Titles, inputFile.nextLine());
getQuantity(Quantities, inputFile.nextInt());
getPrice(Prices, inputFile.nextDouble());
getType(Types, inputFile.next());
System.out.println("Title: " + Titles.get(count));
System.out.println(" Product Type: " + Types.get(count));
System.out.println(" Price: " + Prices.get(count));
System.out.println(" Quantity: " + Quantities.get(count));
System.out.println();
count++;
inputFile.next();
}
System.out.println("-----------------------------------------------------------------");
System.out.println("Total products in database: " + count);
System.out.println("Largest quantity item: " + largestQuantity);
System.out.println("Highest total dollar item: ");
System.out.println("Smallest quantity item: ");
System.out.println("Lowest total dollar item: ");
System.out.println("-----------------------------------------------------------------");
inputFile.close();
} catch (IOException e) {
System.out.println("There was a problem reading from " + database);
}
in.close();
}
private static String getFile(Scanner inScanner) {
System.out.print("Enter database filename: ");
String fileName = inScanner.nextLine();
return fileName;
}
private static void getTitle(ArrayList<String> Titles, String title) {
Titles.add(title);
}
private static void getType(ArrayList<String> Types, String type) {
Types.add(type);
}
private static void getPrice(ArrayList<Double> Prices, double price) {
Prices.add(price);
}
private static void getQuantity(ArrayList<Integer> Quantities, int quantity) {
Quantities.add(quantity);
}
private static void getLargestQuantityItem(ArrayList<Integer> Quantities){
Integer largestQuantity = Collections.max(Quantities);
}
}
Here is the output and the error I'm receiving:
Enter database filename:
Product Summary Report
------------------------------------------------------------
Title: The Shawshank Redemption
Product Type: DVD
Price: 19.95
Quantity: 100
Title: Dark Knight
Product Type: DVD
Price: 19.95
Quantity: 50
Title:
Product Type: DVD
Price: 9.95
Quantity: 137
Title: Girl With The Dragon Tattoo
Product Type: Book
Price: 14.95
Quantity: 150
Title:
Product Type: DVD
Price: 9.95
Quantity: 55
Title: Game of Thrones
Product Type: Book
Price: 8.95
Quantity: 100
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at Project01.main(Project01.java:31)
In reference to this post and your txt file.
Add inputFile.nextLine() after your nextInt(), nextDouble() method.
getQuantity(Quantities, inputFile.nextInt());
inputFile.nextLine();
getPrice(Prices, inputFile.nextDouble());
inputFile.nextLine();
Change below code
getType(Types, inputFile.nextLine());
And remove your inputFile.next(); at the end of your while loop.
Second approach will be just add if block around your next(); method call.
if (inputFile.hasNext()) {
inputFile.next();
}
The problem was that next(); at the end of the while loop was reading the next element. But at the end of file after Book there was nothing to read so it was throwing Exception at that line.
Update:
largestQuantity is a local variable, it can not be accessed outside the method. You should return it from getLargestQuantityItem method. So change the return type of your method and then return the max value.
private static Integer getLargestQuantityItem(ArrayList<Integer> Quantities){
return Collections.max(Quantities);
}
And in main method
To get Largest quantity item:
System.out.println("Lowest total dollar item: ");
Integer largestQuantityMainVariable = getLargestQuantityItem(Quantities);
System.out.println("Largest quantity : " + largestQuantityMainVariable);
int index;
for (int i = 0; i < Quantities.size(); i++) {
if (Quantities.get(i) != null && Quantities.get(i).equals(largestQuantityMainVariable)) {
index = i;
break;
}
}
System.out.println("Largest quantity item : " + Titles.get(index));
Update 2:
For the question in the comments The only thing I have left is to find the highest and lowest total dollar value. I need to somehow take the quantity times the price and then look for the max and min value out of those values
private static List<Double> generateTotalPriceList(List<Double> prices, List<Integer> quantities) {
List<Double> totalPriceList = null;
if (prices != null && prices.size() > 0
&& quantities != null && quantities.size() > 0) {
if (prices.size() == quantities.size()) {
totalPriceList = new ArrayList<Double>();
double totalValue;
for (int i = 0; i < prices.size(); i++) {
totalValue = prices.get(i) * (double) quantities.get(i);
totalPriceList.add(totalValue);
}
}
}
return totalPriceList;
}
In main method
List<Double> totalPriceList = generateTotalPriceList(Prices, Quantities);
Now you can follow the procedure as we did for Quantity.

Calculating Bill (Array and Do Loop for Java) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble with my online lab, I'm given this code below and I can only modify the places where it says '// FIX ME'. I've already added the following answers in the blanks but I still don't have it quite right. I was thinking about writing another code on top asking for how many items I would like to input and then creating a DO Loop centered around that but this isn't what the question wants from me. It's possible that I'm just looking at this the wrong way, any help would be appreciated!
Here is the Lab;
The following program should input a list of items, including the description of the item, the number of items purchased and the unit price of the item; then calculate the total bill. The input of the list is complete when "Finish" is entered for the description. Complete the program so that it works correctly.
import java.util.Scanner;
public class CalculateBill {
public static void main( String[] args ) {
double sum = 0;
double cost;
int items;
double unitPrice;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the name of the item (Finish to end):");
String description = scan.next();
while( items != 0 ) { // FIX-ME
System.out.println("Please enter the quantity of " + description + ": " );
items = scan.nextInt();
System.out.println("Please enter the unit price of " + description + ": ");
unitPrice = scan.nextDouble();
cost = Price++ ; // FIX-ME
System.out.printf("Cost of %d %s(s) is $%.2f%n", items, description, cost);
sum = sum+1; // FIX-ME
System.out.println("Please enter the name of the item (Finish to end):");
description = scan.next();
}
System.out.printf("The total bill is $%.2f%n" ??? ); // FIX-ME
}
}
This is what I did to get it working:
import java.util.Scanner;
public class CalculateBill {
public static void main( String[] args ) {
double sum = 0;
double cost = 0;
int items=0;
double unitPrice;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the name of the item (f to end):");
// changed to f as I don't want to have to type Finish every time
String description = scan.next();
while( !description.equals("f") ) { // FIXED
System.out.println("Please enter the quantity of " + description + ": " );
items = scan.nextInt();
System.out.println("Please enter the unit price of " + description + ": ");
unitPrice = scan.nextDouble();
cost = items*unitPrice ; // FIXED
System.out.printf("Cost of %d %s(s) is $%.2f%n", items, description, cost);
sum += cost; // FIXED
System.out.println("Please enter the name of the item (F to end):");
description = scan.next();
}
System.out.printf("The total bill is $%.2f%n", sum); // FIXED
}
}

Printing out array lists

I messed up trying to print out this array list what am I doing wrong I've tried multiple times but when ever it prints it outputs null.
import java.util.ArrayList;
import java.util.Arrays;
import java.text.NumberFormat;
import java.util.Scanner;
//Class header
public class ShoppingCart {
// Start of main method
public static <Item> void main(String[] args) {
// Declare and instantiate a variable that is an ArrayList that can hold
// Product objects
ArrayList<Product> item = new ArrayList<Product>();
// Declare necessary local variables here
String Name = null;
double Price = 0;
int Quantity = 0;
String Seller = null;
Scanner scan = new Scanner(System.in);
String Shop = "yes";
// Write a print statement that welcome's the customer to our shop
/**
*
* create a do while that will be keep looping as long as user wants to
* continue shopping
*/
Product im = new Product(Name, Price, Quantity, Seller);
// do while loop start
do {
// Ask user to enter product name and store it in appropriate local
// variable
System.out.print("Please Enter the Product Name: ");
Name = scan.next();
// Ask user to enter product price and store it in appropriate local
// variable
System.out.print("Please Enter the Price of the Product: ");
Price = scan.nextDouble();
// Ask user to enter quantity and store it in appropriate local
// variable
System.out.print("Please enter the Quantity: ");
Quantity = scan.nextInt();
// Ask user to enter product manufacturer name and store it in
// appropriate local variable
System.out.print("Please Enter the Manufacturer: ");
Seller = scan.next();
System.out.print("Would you like to continue shopping?");
Shop = scan.next();
// create a new Product object using above inputed values
Product item2 = new Product(Name, Price, Quantity, Seller);
// add above created Product to the ArrayList cart if Product has
// available stock
// if stock not available inform user requested product is out of
// stock
// Ask user whether wants to continue shopping
// set the do while loop to continue to loop if Yes option is
// selected
} while (Shop.equals("Yes"));
System.out.println("Product Unit Price Quantity SubTotal");
System.out.println(Name + " " + (Price) + " " + Quantity + " " + (Price * Quantity));
System.out.println("00"); System.out.println(item);
// do while loop end
// header for shopping cart contents
// print details of each product added to the ArrayList
// calculate total price of the shopping cart
// print the total price of the shopping cart
}// end of main method
}// end of Shop class
First of all, why are you doing this
public static <Item> void main(String[] args) {
SHould be
public static void main(String[] args) {
To print the ArrayLIst just do this
System.out.println("Name\tPrice\tQuantity\tSeller\tTotal")
for (Product p : item){
double total = p.price * p.quantity;
System.out.println(p.name + "\t" + p.price + "\t" p.quantity + "\t" + p.seller + "\t" + total);
}
But first you need to add something to the list
Product item2 = new Product(Name, Price, Quantity, Seller);
item.add(item2);
Or even a cleaner looking idea would be override the toString method in the Product class
public class Product {
String name;
String Seller;
double price;
int quantity;
public Product(String name, double price, int quantity, String seller){
this.name = name;
this.seller = seller;
this.price = price;
this.seller = seller;
}
public String toString(){
double total = p.price * p.quantity;
return name + "\t" + price + "\t" quantity + "\t" + seller + "\t" + total;
}
}
To print from list just do this.
for (Product p : item){
System.out.println(p);
}
its because you never add the item2 to the arraylist item
just add
item.add(item2)
There are quite a few errors in your program.
First off, the reason nothing is being printed when you try printing your arraylist is because you never add any element to your array list, to do so you must use the following method.
arrayListName.add(elementToAdd);
Secondly your main method is incorrect, instead of
public static <Item> void main(String[] args) {
it should be
public static void main (String[] args) {

MissingFormatArgumentException error

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

Categories