מהי שיטת Java string.format()?
שיטת Java string format() משמשת לעיצוב מחרוזות, מספרים שלמים, ערכים עשרוניים וכן הלאה, על ידי שימוש במפרטי פורמטים שונים. שיטה זו מחזירה את המחרוזת המעוצבת באמצעות המקום הנתון, הפורמט שצוין והארגומנטים. אם לא מסופק מקום, הוא משתמש בכתובת ברירת המחדל לעיצוב המחרוזות. ה- string.format() היא השיטה הסטטית של המחלקה Java String .
public static String format(Locale loc, String format, Object… args)
public static String format(String format, Object… args)
פרמטרים
- ערך המקום שייושם בשיטת format() .
- ציון הפורמט של מחרוזת הפלט.
- מספר הארגומנטים עבור מחרוזת הפורמט נע בין 0 לרבים.
- NullPointerException , אם הפורמט הוא null אז NullPointerException נזרק.
- IllegalFormatException , אם הפורמט שצוין אינו חוקי, או שלא סופקו ארגומנטים מספיקים, החריג הזה נזרק.
מפרטי פורמט
הבה נסתכל על כמה מפרטים נפוצים.מפרט | תיאור |
---|---|
%s, %S | מעצב מחרוזת. |
%d | מספר שלם עשרוני, המשמש עבור מספרים שלמים בלבד. |
%o | מספר שלם אוקטלי, המשמש עבור מספרים שלמים בלבד. |
%f, %F | עבור מספרים עשרוניים, משמש למספרי נקודה צפה. |
%x, %X | מספר שלם הקסדצימלי, המשמש עבור מספרים שלמים בלבד. |
שיטות Java String.format() דוגמאות
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));
}
}
תְפוּקָה
שיטת 234 format() 99.990000 63 f 143
דוגמא
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));
}
}
תְפוּקָה
התוצאה היא הקסדצימלית: 63
דוגמא
// 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));
}
}
תְפוּקָה
מספר: 9,999,999 מספר בגרמנית: 9.999.999
GO TO FULL VERSION