printf无法使用Strings

时间:2016-02-12 06:58:05

标签: java class object exception printf

我正在尝试使这个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)

值:

必然是程序中的实际代码)

stock.symbol = "ORCL";
stock.name = "Oracle Corporation";
stock.previousClosingPrice = 34.5;
stock.currentPrice = 34.35;

'Stock'类:

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;
    }
}

免责声明:这是一项家庭作业,但我已经为它编写了完整的代码。我只需要解决这个错误,并得到我的导师的许可,发布这样的问题。

1 个答案:

答案 0 :(得分:3)

  

第二个%是故意的,将14.5变为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

  

通常,格式说明符具有以下语法:

%[argument_index$][flags][width][.precision]conversion
     

下表总结了支持的转化次数:

...
'%'   percent The result is a literal '%' ('\u0025')
...