我在代码“ main”中的异常中不断收到此异常
java.util.IllegalFormatConversionException:f!= java.lang.Integer
我不知道如何解决格式转换。帮助将不胜感激。
import javax.swing.JOptionPane;
public class SoftwareSales {
public static void main(String[] args) {
// This program displays the amount of discount (if any) and the total amount of the purchase after the discount.
String userInput;
String userOutput;
double packagePrice = 99;
int userNumberOfPackages;
double discount = 0;
double subTotal = 0;
double total = 0;
userInput = JOptionPane.showInputDialog( "Enter how many packages you are buying" );
userNumberOfPackages = Integer.parseInt( userInput );
if ( userNumberOfPackages < 10){
subTotal = packagePrice * userNumberOfPackages;
discount = 0;
total = subTotal - discount;
} else if ( userNumberOfPackages < 20 ){
subTotal = packagePrice * userNumberOfPackages;
discount = ( (double)20/100) * subTotal;
total = subTotal - discount;
} else if ( userNumberOfPackages < 50 ){
subTotal = packagePrice * userNumberOfPackages;
discount = ( (double)30/100) * subTotal;
total = subTotal - discount;
} else if ( userNumberOfPackages < 100 ){
subTotal = packagePrice * userNumberOfPackages;
discount = ( (double)40/100) * subTotal;
total = subTotal - discount;
} else{
subTotal = packagePrice * userNumberOfPackages;
discount = ( (double)50/100) * subTotal;
total = subTotal - discount;
}
userOutput = String.format( "Packages purchased: \nSubtotal: $\nDiscount: $\nTotal: $", userNumberOfPackages, subTotal,
discount, total);
JOptionPane.showMessageDialog( null, userOutput);
System.exit(0);
}
}
答案 0 :(得分:0)
让我们总结一下评论,因为它们不仅可以解决您的问题,而且可以描述任何问题的过程。
适用于您的情况:
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302) at
java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2806) at
java.util.Formatter$FormatSpecifier.print(Formatter.java:2753) at
java.util.Formatter.format(Formatter.java:2520) at
java.util.Formatter.format(Formatter.java:2455) at
java.lang.String.format(String.java:2940) at
SoftwareSales.main(SoftwareSales.java:45)
只有SoftwareSales.java是您自己编写的。因此问题出在SoftwareSales.java,第45行。
是这一行:
userOutput = String.format( "Packages purchased: \nSubtotal: $\nDiscount: $\nTotal: $", userNumberOfPackages, subTotal,
discount, total);
使用String.format()
,您想在字符串中插入4个数字。但是应该将它们插入哪里?没有Placehoder。
看一些documentation:
format:格式字符串
a format string需要带有%
的内容。 %f
可能是浮点数,%d
可能是十进制数。
最后(未试用):
userOutput = String.format( "Packages purchased: %d\n
Subtotal: $%f\n
Discount: $%f\n
Total: $%f",
userNumberOfPackages, subTotal, discount, total);