[英]Exception in thread “main” java.lang.IllegalArgumentException: Cannot format given Object as a Number
I need to display 2 decimal point but I don't get it how to do It.我需要显示 2 个小数点,但我不知道该怎么做。
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Number
线程“主”java.lang.IllegalArgumentException 中的异常:无法将 Object 格式化为数字
import java.text.DecimalFormat;
import java.util.Scanner;
public class ShoppingOrders {
public static void main(String[] args) {
double itemPrice, shippingFeeRate, shippingFee,totalCost;
String nameItem;
Scanner myScanner= new Scanner (System.in);
DecimalFormat df = new DecimalFormat("#.00");
nameItem = myScanner.nextLine();
itemPrice = myScanner.nextDouble();
shippingFeeRate = myScanner.nextDouble();
shippingFee =shippingFeeRate*itemPrice;
totalCost = shippingFee+itemPrice;
System.out.println ("Costs for "+nameItem);
System.out.println (df.format("Item Price: $" +itemPrice));
System.out.println (df.format("Shipping Fee: $"+ shippingFee));
System.out.println (df.format("Total Cost: $"+totalCost));
}
}
You are using DecimalFormat.format(...)
incorrectly.您使用
DecimalFormat.format(...)
不正确。 You don't pass it a String
.您没有将其传递给
String
。 You pass it an object that represents a number.你传递给它一个代表数字的 object。 (Or a primitive number type which will be boxed to an object that represents a number.)
(或将被装箱为代表数字的 object 的原始数字类型。)
For example:例如:
df.format(itemPrice) // itemPrice will be boxed to a Double
So if you want to include a message in the output, you might do this:因此,如果您想在 output 中包含一条消息,您可以这样做:
System.out.println("Item Price: $" + df.format(itemPrice));
Alternatively, you could use String.format(...)
and specify the number of digits after the decimal point in the format specifier.或者,您可以使用
String.format(...)
并在格式说明符中指定小数点后的位数。
DecimalFormat.format(...)
is for formatting a number. DecimalFormat.format(...)
用于格式化数字。 In your case, you added a String to the double, which turns it into a String
, which DecimalFormat.format(...)
doesn't support.在您的情况下,您将 String 添加到 double 中,这会将其转换为
String
, DecimalFormat.format(...)
不支持。 Instead, use:相反,使用:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
double itemPrice, shippingFeeRate, shippingFee,totalCost;
String nameItem;
Scanner myScanner= new Scanner (System.in);
DecimalFormat df = new DecimalFormat("#.00");
nameItem = myScanner.nextLine();
itemPrice = myScanner.nextDouble();
shippingFeeRate = myScanner.nextDouble();
shippingFee =shippingFeeRate*itemPrice;
totalCost = shippingFee+itemPrice;
System.out.println ("Costs for "+nameItem);
System.out.println ("Item Price: $" +df.format(itemPrice));
System.out.println ("Shipping Fee: $"+ df.format(shippingFee));
System.out.println ("Total Cost: $"+df.format(totalCost));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.