This program currently gives me the following error: Exception in thread \"main\
ID: 3637200 • Letter: T
Question
This program currently gives me the following error:Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Float
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at Sales.main(Sales.java:75)
Can someone help me correct this problem?
Thanks.
Here is the code:
import java.util.Scanner;
public class Sales
{
public static void main( String[] args )
{
float product1 = 0,
product2 = 0,
product3 = 0,
product4 = 0,
product5 = 0;
int productId = 1,
quantity = 0;
String inputString;
Scanner kbinput = new Scanner(System.in);
//while loop to ask user for product number until flag value entered
while( productId != 0 )
{
System.out.print( "Enter product id 1 - 5, or 0 to stop: ");
inputString = kbinput.nextLine();
productId = Integer.parseInt( inputString );
if ( productId >= 1 && productId <=5 )
{
System.out.print( "Enter the quantity sold: ");
inputString = kbinput.nextLine();
}
else if ( productId == 0)
System.out.print("Program terminates! ");
//increment the total for the item by the
//price times the quantity sold
switch( productId )
{
case 1:
product1 += quantity * 2.98;
break;
case 2:
product2 += quantity * 4.50;
break;
case 3:
product3 += quantity * 9.98;
break;
case 4:
product4 += quantity * 4.49;
break;
case 5:
product5 += quantity * 6.87;
break;
}
}
System.out.printf("Number sold: %d.2f " , product1);
System.out.println( product2);
System.out.println( product3);
System.out.println( product4);
System.out.println( product5);
}
}
Explanation / Answer
he reason is becase wrong conversion label was used. To recall, conversion label is ‘%’ sign followed by a letter b, c, d, f, or s inside System.out.format(). In the above example, %d meant that an integral type (byte, Byte, short, Short, int, Integer, long, Long, BigInteger) would be used. However, finally there was a floating point passed (avgAge). This example would work if this conversion label were used: %f. change this line System.out.printf("Number sold: %d.2f " , product1); as System.out.printf("Number sold: %2f " , product1);
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.