How to use java.String.format in Scala?

3

I'm trying to use the .format method of a String. But if I put% 1,% 2, etc. in the string, the java.util.UnknownFormatConversionException exception is thrown by pointing to confusing Java code:

private void checkText(String s) {

    int idx;

    // If there are any '%' in the given string, we got a bad format
    // specifier.
    if ((idx = s.indexOf('%')) != -1) {
        char c = (idx > s.length() - 2 ? '%' : s.charAt(idx + 1));
        throw new UnknownFormatConversionException(String.valueOf(c));
    }
}

I conclude that the % character is forbidden. If so, what should I use as arguments to be replaced?

I use Scala 2.8.

    
asked by anonymous 10.08.2014 / 21:14

1 answer

2

You do not need to use numbers to indicate position. By default, the position of the argument is simply the order in which it appears in the string.

See an example of how to use this:

String result = String.format("O método format é %s!", "legal");
// resultado igual a "O método format é legal!".

You will always use a % followed by some other character so that the method knows how to show the string. %s is usually the most common, and means that the argument should be treated as a string.

Some examples to give you an idea:

// podemos especificar o # de decimais para um número de ponto flutuante:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// "10 / 3 = 3.33"

// separador de milhar:
result = String.format("O elefante pesa %,d gramas.", 1000000);
// result now equals  "O elefante pesa 1,000,000 gramas."

String.format uses java.util.Formatter . For complete documentation, see Formatter javadocs .

    
10.08.2014 / 21:21