Was ist die Java-Methode string.format()?
Die Java- Methode string format() wird zum Formatieren von Zeichenfolgen, Ganzzahlen, Dezimalwerten usw. mithilfe verschiedener Formatspezifizierer verwendet. Diese Methode gibt die formatierte Zeichenfolge unter Verwendung des angegebenen Gebietsschemas, des angegebenen Formatierers und der Argumente zurück. Wenn kein Gebietsschema angegeben ist, wird das Standardgebietsschema zum Formatieren der Zeichenfolgen verwendet. string.format () ist die statische Methode der Java- String- Klasse.
public static String format(Locale loc, String format, Object… args)
public static String format(String format, Object… args)
Parameter
- Der Gebietsschemawert, der auf die format()- Methode angewendet wird.
- Angabe des Formats der Ausgabezeichenfolge.
- Die Anzahl der Argumente für die Formatzeichenfolge reicht von 0 bis viele.
- NullPointerException : Wenn das Format null ist, wird eine NullPointerException ausgelöst.
- IllegalFormatException : Wenn das angegebene Format unzulässig ist oder nicht genügend Argumente angegeben werden, wird diese Ausnahme ausgelöst.
Formatspezifizierer
Schauen wir uns einige häufig verwendete Spezifizierer an.Spezifizierer | Beschreibung |
---|---|
%s, %S | Ein String-Formatierer. |
%D | Eine dezimale Ganzzahl, die nur für Ganzzahlen verwendet wird. |
%Ö | Eine oktale Ganzzahl, die nur für Ganzzahlen verwendet wird. |
%f, %F | Für Dezimalzahlen, wird für Gleitkommazahlen verwendet. |
%x, %X | Eine hexadezimale Ganzzahl, die nur für Ganzzahlen verwendet wird. |
Beispiele für die Java String.format()-Methode
class Main {
public static void main(String[] args) {
// Integer value
System.out.println(String.format("%d", 234));
// String value
System.out.println(String.format("%s", "format() method"));
// Float value
System.out.println(String.format("%f", 99.99));
// Hexadecimal value
System.out.println(String.format("%x", 99));
// Char value
System.out.println(String.format("%c", 'f'));
// Octal value
System.out.println(String.format("%o", 99));
}
}
Ausgabe
234 format()-Methode 99,990000 63 f 143
Beispiel
class Main {
public static void main(String[] args) {
int n1 = 99;
// using two different specifiers for formatting the string
System.out.println(String.format("%s\nhexadecimal: %x", "Result is", n1));
}
}
Ausgabe
Ergebnis ist hexadezimal: 63
Beispiel
// to use Locale
import java.util.Locale;
class Main {
public static void main(String[] args) {
int number = 9999999;
// using the default locale if none specified
System.out.println(String.format("Number: %,d", number););
// using the GERMAN locale as the first argument
System.out.println(String.format(Locale.GERMAN, "Number in German: %,d", number));
}
}
Ausgabe
Nummer: 9.999.999 Nummer auf Deutsch: 9.999.999
GO TO FULL VERSION