-1

I am new to Java and trying to create a table with quantities and price of the provided input items.

package new.learnprogramming;

import java.text.NumberFormat;

public class Main {

public static void main(String[] args) {

NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
String apples = "Apples";
int appleQuantity = 8;
int applePrice = 400;
String oranges = "Oranges";
int orangeQuantity = 10;
int orangePrice = 150;

String column1Heading = "Fruits";
String column2Heading = "Quantity";
String column3Heading = "Price";

System.out.printf("%10s %10s %5s%n", column1Heading, column2Heading, column3Heading);
System.out.printf("%10s %8d %11d cents%n", apples, appleQuantity , currencyFormat.format(applePrice));
System.out.printf("%11s %8d %10d cents%n", oranges, orangeQuantity, currencyFormat.format(orangePrice));


}
}

I am trying to get the output as:

Fruits Quantity Price Apples 8 $400.00 cents Oranges 10 $150.00 cents

But, the output is coming up as:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4426)
at java.base/java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2938)
at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2892)
at java.base/java.util.Formatter.format(Formatter.java:2673)
at java.base/java.io.PrintStream.format(PrintStream.java:1053)
at java.base/java.io.PrintStream.printf(PrintStream.java:949)
at com.company.Main.main(Main.java:22)
user207421
  • 305,947
  • 44
  • 307
  • 483
Priyankana
  • 35
  • 1
  • 4

3 Answers3

0

NumberFormat.format(long) returns a String (and the format for a String is %s, like your first column). Like,

System.out.printf("%10s %8d %11s cents%n", apples, 
        appleQuantity, currencyFormat.format(applePrice));
System.out.printf("%11s %8d %10s cents%n", oranges, 
        orangeQuantity, currencyFormat.format(orangePrice));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Simply fix format specifiers. %d is for decimal.

        System.out.printf("%10s %10s %5s%n", column1Heading, column2Heading, column3Heading);
        System.out.printf("%10s %8d %11s cents%n", apples, appleQuantity , currencyFormat.format(applePrice));
        System.out.printf("%11s %8d %10s cents%n", oranges, orangeQuantity, currencyFormat.format(orangePrice));
Eduard Dubilyer
  • 991
  • 2
  • 10
  • 21
0

NumberFormat.format() (see this) returns a String, not an int/long/double/or similar. You're format is expecting the latter because you are using %d, but you should be using %s so that it properly expects a String.

Luke Hollenback
  • 769
  • 6
  • 15