我试图让这个 printf 工作,但我不断收到一个异常,提示第一个 '%' 运算符。我像这样多次使用 printf,从来没有遇到过问题。我正在使用 eclipse 。
我的问题:
为什么我的语句不起作用,我怎样才能让它起作用?
注意事项:
第18行,第二个%
用来表示一个文字%
printf 语句:
14 System.out.printf("Symbol: %s\n"
15 + "Name: %s\n"
16 + "Previous Closing Price: %1.2f\n"
17 + "Current Price: %1.2f\n"
18 + "Change: %1.2f%",
19 stock.symbol,
20 stock.name,
21 stock.previousClosingPrice,
22 stock.currentPrice,
23 stock.getChangePercent());
错误:
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '%'
at java.util.Formatter.checkText(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at No8_2.main(No8_2.java:14)
值(value)观:
(不一定是程序中的实际代码)
stock.symbol = "ORCL";
stock.name = "Oracle Corporation";
stock.previousClosingPrice = 34.5;
stock.currentPrice = 34.35;
'股票'类:
class Stock{
//Stock Object
String symbol;
String name;
double previousClosingPrice;
double currentPrice;
Stock(String sym, String nam){
//Initialize Instance Vars
this.symbol = sym;
this.name = nam;
}
public double getChangePercent(){
//Return (in %) the change in price
return ((currentPrice - previousClosingPrice)/previousClosingPrice)*100;
}
}
免责声明:这是一项家庭作业,但我已经为它完整地编写了代码。我只需要克服这个错误,并获得我的导师的许可,就可以发布这样的问题。
最佳答案
The second % is intentional, to turn 14.5 into 14.5%
您需要使用第二个 %
转义 %
:
System.out.printf("Symbol: %s\n"
+ "Name: %s\n"
+ "Previous Closing Price: %1.2f\n"
+ "Current Price: %1.2f\n"
+ "Change: %1.2f%%",
// ^
stock.symbol,
stock.name,
stock.previousClosingPrice,
stock.currentPrice,
stock.getChangePercent());
另见 https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html :
In general, the format specifier has the following syntax:
%[argument_index$][flags][width][.precision]conversion
The following table summarizes the supported conversions:
... '%' percent The result is a literal '%' ('\u0025') ...
关于java - printf 不适用于字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35356598/