How to use java.String.Scala format?

I'm trying to use the .format method of a String. But if I put %1, %2, etc. in the string, the java Exception.useful.UnknownFormatConversionException is thrown, 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 override?

I use scale 2.8.

Author: Daniel Cukier, 2014-08-10

1 answers

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.

Here's 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 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 Use a java.util.Formatter. For complete documentation, see formatter javadocs .

 2
Author: Daniel Cukier, 2014-08-10 19:21:38