Bölüm 21 Çıktıyı Biçemleme Kağıda ya da ekrana gönderilen bilgisayar çıktıları kolay okunur ve anlaşılır biçime sokulur. Java nın ilk dört sürümünde çıktının biçimlendirilebilmesi için print() ya da println() metotları kullanılırdı. Bu metotlarla çıktıyı biçemlemek için gerekli dolguları (padding) yapmak programcıya düşen bir görevdi. Java 5 bu iş için Formatter sınıfını hazırlamıştır. Bu sınıfta sayısal ya da metin çıktılarını istediğimiz biçeme sokmaya yarayacak öğeler vardır. Bunların başlıcalarını aşağıda örnekler üzerinde göreceğiz. Formatter sınıfında tanımlanan metotlardan biri olan format() metodu, esasta C dilindeki printf() fonksiyonunun işlevine benzer işlevleri gören bir metottur. Tabii, bu metot Formatter sınıfına ait olduğu için nesne yönelimli programlamanın avantajlarına sahiptir. Dolayısıyla, printf() fonksiyonundan daha işlevseldir. Her durumda, daha önce C dilini görenler format() metoduna kolayca aşina olacaklardır. Formatter sınıfı Object sınıfından türetilmiştir. java.lang.object java.util.formatter Format() metodu public abstract String format(logrecord record) Sayıların Stringe Dönüştürülmesi Concatenation (+) (+) concatanation operatörü kullanılarak sayılar Stringe dönüştürülebilir. (+) operatörü ile bir Stringle birleşen her sayı otomatik olarak Stringe dönüşür. Aşağıdaki programda x tamsayı, s String tipnden olduğu için s = x; ataması geçersizdir; derleyici hata verir. Ama s = + x; ataması geçerlidir. Çünkü boş Stringi ile 37 tamsayısı birleştirilmektedir. Burada (+) concatanation operatörü işleme giren terimlerin hepsini Stringe dönüştürmektedir. Programı inceleyiniz ve deyimlerin ne yaptığını anlayınız. public class KesirliSayıBiçemle { /** * @param args */ 1
public static void main(string[] args) { int x = 37; String s; //s = x; // Geçersiz s = "" + x; // 37 tamsayısı "37" Stringine dönüşür System.out.println(s); s = x + " is OK"; // s Stingine "37 is OK" değerini atar System.out.println(s); s = "" + 3.5; // s Stringine "3.5" değerini atar System.out.println(s); s = "" + 1.0/3.0; // s = "0.3333333333333333" ataması System.out.println(s); 37 37 is OK 3.5 0.3333333333333333 String.format("%.5g%n", 0.912385); // 0.91239 String.format("%.5g%n", 0.912300); // 0.91230 DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); // 0.91238 format() metodunun ilk parametresi bir stringdir; bu string daha sonra gelen sayıları nasıl bir stringe dönüştüreceğini belirler. Örneğin, %nd : tamsayıyı n haneye sağa yanaşık olarak yazar. Örneğin, int n = 2; System.out.format("%3d", n); // 2 System.out.format(" %3d ", n); // 2 import java.io.*; import java.util.formatter; /** * Demonstrate the java.util.formatter capabilities for * formatting primitive types and sending them to a file. **/ public class FormatWriteFileApp { public static void main (String arg[]) { Formatter formatter = null; 2
File file = null; // Get the file from the argument line. if (arg.length > 0) file = new File (arg[0]); // Else use a default file name. if (file == null) { System.out.println ("Default: textoutput.txt"); file = new File ("textoutput.txt"); // Send formatted output to the file. try { formatter = new Formatter (file); catch (FileNotFoundException e) { // File not found exception thrown since this is a new // file name. However, Formatter will create the new file. formatter.format ("Text output with Formatter. %n"); formatter.format ("Primitives converted to strings: %n"); boolean a_boolean = false; byte a_byte = 114; short a_short = 1211; int an_int = 1234567; long a_long = 987654321; float a_float = 983.6f; double a_double = -4.297e-15; formatter.format ("boolean = %9b %n", a_boolean); formatter.format ("byte = %9d %n", a_byte); formatter.format ("short = %9d %n", a_short); formatter.format ("int = %9d %n", an_int); formatter.format ("long = %9d %n", a_long); formatter.format ("float = %9.3f %n", a_float); formatter.format ("double = %9.2e %n", a_double); // Need to flush the data out of the buffer. formatter.flush (); formatter.close (); // main // class FormatWriteFileApp %nf : float sayıyı n haneye sağa yanaşık olarak yazar, %nd : tamsayıyı n haneye sağa yanaşık olarak yazar, 3
The format() method's first parameter is a string that specifies how to convert a number. For integers you would typically use a "%" followed by the number of columns you want the integer to be right justified in, followed by a decimal conversion specifier "d". The second parameter would be the number you want to convert. For example, int n = 2; System.out.format("%3d", n); This would print the number in three columns, that is with two blanks followed by 2. You can put other non-% characters in front or back of the conversion specification, and they will simply appear literally. For example, int n = 2; System.out.format(" %3d ", n); would print 2 Tamsayı Biçemleri DecimalFormat(): 0 simgesi Çıktıda bir haneyi temsil eder. Eğer hiç hane yoksa 0 sayısı çıkar. Örnekler: NumberFormat formatter = new DecimalFormat("000000"); String s = formatter.format(-1234.567); // -001235 Kesirli sayı en yakın tamsayıya yuvarlanıyor. Bu esnada atılan kesir kısmı yarımdan büyük olduğu için, tamsayı çıktının birler hanesi 1 artmıştır. # simgesi Çıktıda bir hane gösterir. Olmadığı zaman çıktıda onun yerine hiç bir rakam gelmez: Örnekler: formatter = new DecimalFormat("##"); s = formatter.format(-1234.567); // Çıktı : -1235 s = formatter.format(0); // 0 formatter = new DecimalFormat("##00"); s = formatter.format(0); // 00 4
. simgesi Onlu çekesini (ondalık ayracı) temsil eder. Örnekler: formatter = new DecimalFormat(".00"); s = formatter.format(-.567); // -.57 formatter = new DecimalFormat("0.00"); s = formatter.format(-.567); // -0.57 formatter = new DecimalFormat("#.#"); s = formatter.format(-1234.567); // -1234.6 formatter = new DecimalFormat("#.######"); s = formatter.format(-1234.567); // -1234.567 formatter = new DecimalFormat(".######"); s = formatter.format(-1234.567); // -1234.567 formatter = new DecimalFormat("#.000000"); s = formatter.format(-1234.567); // -1234.567000, simgesi Çıktıyı yüzlük gruplarına ayırır: formatter = new DecimalFormat("#,###,###"); s = formatter.format(-1234.567); // -1,235 s = formatter.format(-1234567.890); // -1,234,568 ; simgesi Negatif sayıların çıktısını başka biçemde göstermek için kullanılır: formatter = new DecimalFormat("#;(#)"); s = formatter.format(-1234.567); // (1235) simgesi 5
Çıktıya istenen karakter dizisini (literal) gönderir: formatter = new DecimalFormat("'#'#"); s = formatter.format(-1234.567); // -#1235 formatter = new DecimalFormat("'abc'#"); s = formatter.format(-1234.567); // -abc1235 import java.util.formatter; public class Hizalama { Formatter // Right justify by default fmt.format(" %10.2f ", 123.123); // Now, left justify. fmt.format(" %-10.2f ", 123.123); 123,12 123,12 import java.util.calendar; import java.util.formatter; public class DateTimeDemo { Formatter Calendar cal = Calendar.getInstance(); // Display standard 12-hour time format. fmt.format("%tr", cal); 6
// Display complete time and date information. fmt.format("%tc", cal); // Display just hour and minute. fmt.format("%tl:%tm", cal, cal); // Display month by name and number. fmt.format("%tb %tb %tm", cal, cal, cal); 10:13:22 AM Paz Eyl 12 10:13:22 EEST 2010 10:13 Eylül Eyl 09 import java.util.calendar; import java.util.formatter; public class DateTimeDemo { Formatter Calendar cal = Calendar.getInstance(); // Standart 12 saat zaman biçeminde yaz. fmt.format("%tr", cal); // Tarih ve zamanı tam biçemiyle yaz. fmt.format("%tc", cal); // Yalnız saat ve dakikayı göster. 7
fmt.format("%tl:%tm", cal, cal); // Ay adını ve sırasını göster. fmt.format("%tb %tb %tm", cal, cal, cal); 10:19:51 AM Paz Eyl 12 10:19:51 EEST 2010 10:19 Eylül Eyl 09 import java.util.*; public class AlanGenişliğiDemo { Formatter fmt; for(int i=1; i <= 10; i++) { fmt.format("%4d %4d %4d", i, i*i, i*i*i); 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 8
import java.util.*; public class Biçem02 { Formatter for(double i=1000; i < 1.0e+10; i *= 100) { fmt.format("%g ", i); 1000.00 1000.00 100000 1000.00 100000 1.00000e+07 1000.00 100000 1.00000e+07 1.00000e+09 import java.util.*; public class Biçem03 { Formatter fmt.format(" %f %n %12f %n %012f ", 10.12345, 10.12345, 10.12345); 10,123450 10,123450 00010,123450 9
public class SayısalBiçemler { System.out.println("Farklı biçemlerde yazılmış " + "bazı sayılar:\n"); System.out.printf("Farklı tamsayı gösterimleri: "); System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3); System.out.println(); System.out.printf("Öntanımlı float-sayı gösterimi: %f\n", 1234567.123); System.out.printf("Yüzlüklere ayrılmış biçem : %,f\n", 1234567.123); System.out.printf("Negatif float sayıların öntanımlı gösterimi: %,f\n", - 1234567.123); System.out.printf("Negatif float sayıların () içine alınması : %,(f\n", - 1234567.123); System.out.println(); System.out.printf("Pozitif ve negatif sayıların listesi:\n"); System.out.printf("%,.2f\n%,.2f\n", 1234567.123, -1234567.123); Farklı biçemlerde yazılmış bazı sayılar: Farklı tamsayı gösterimleri: 3 (3) +3 00003 Öntanımlı float-sayı gösterimi: 1234567,123000 Yüzlüklere ayrılmış biçem : 1.234.567,123000 Negatif float sayıların öntanımlı gösterimi: -1.234.567,123000 Negatif float sayıların () içine alınması : (1.234.567,123000) Pozitif ve negatif sayıların listesi: 1.234.567,12-1.234.567,12 import java.util.calendar; import java.util.formatter; public class Tarih01 { Formatter Calendar cal = Calendar.getInstance(); fmt.format("bugünün Tarihi: %te of %<tb, %<ty", cal); 10
Bugünün TArihi: 12 of Eylül, 2010 import java.util.formatter; public class GirişÇıkış { Formatter // 4 ondalık hane yaz. fmt.format("%.4f", 123.1234567); // 16 hanelik yere 2 ondalık haneli yaz. fmt.format("%16.2e", 123.1234567); // En çok 16 karakter yaz. fmt.format("%.16s", "Java ile çıktıyı biçemleme çok kolaydır."); 123,1235 1.23e+02 Java ile çıktıyı 11
Sayıların Üstel Notasyonla Gösterilmesi E nin soluna yazılan 0 ların sayısı kadar çıktının tamsayı hanesi yazılır; yani kayan nokta gösteriminde onlu çekesi o kadar haneden sonra başlar. Örnekler: NumberFormat formatter = new DecimalFormat("0E0"); String s = formatter.format(-1234.567); // -1E3 formatter = new DecimalFormat("00E00"); s = formatter.format(-1234.567); // -12E02 formatter = new DecimalFormat("000E00"); s = formatter.format(-1234.567); // -123E01 formatter = new DecimalFormat("0000000000E0"); s = formatter.format(-1234.567); // -1234567000E-6 Onlu çekesinin soluna ve sağına gelecek minimum hane sayısını belirler: formatter = new DecimalFormat("0.0E0"); s = formatter.format(-1234.567); // -1.2E3 formatter = new DecimalFormat("00.00E0"); s = formatter.format(-1234.567); // -12.35E2 s = formatter.format(-.1234567); // -12.35E-2 # simgesi, çıktıda üstel kısmın çarpanını belirler. E nin solunda ya da sağında yer alan # sayısı kadar hane üstel kısmın solunda ya da sağında yer alabilir. Bu sayı maksimumdur; daha az hane olabilir. Örnekler: formatter = new DecimalFormat("#E0"); // herhangi bir üstel ifade olabilir s = formatter.format(-1234.567); // -.1E4 s = formatter.format(-.1234567); // -.1E0 formatter = new DecimalFormat("##E0"); // üstel ifadenin çarpanı 2 haneli olur s = formatter.format(-1234.567); // -12E2 s = formatter.format(-123.4567); // -1.2E2 s = formatter.format(-12.34567); // -12E0 12
formatter = new DecimalFormat("###E0"); // üstel ifadenin çarpanı 3 haneli olur s = formatter.format(-1234.567); // -1.23E3 s = formatter.format(-123.4567); // -123E0 s = formatter.format(-12.34567); // -12.3E0 s = formatter.format(-1.234567); // -12.3E0 s = formatter.format(-.1234567); // -123E-3 Yöresel Çıktı Biçimleri Locale locale = Locale.CANADA; String string = NumberFormat.getPercentInstance(locale).format(123.45); // 12,345% // Parse try { Number number = NumberFormat.getPercentInstance(locale).parse("123.45%"); // 1.2345 if (number instanceof Long) { // Long value else { // Double value catch (ParseException e) { Yöresel Para Simgelerini Yazdırma Locale locale = Locale.GERMANY; String string = NumberFormat.getCurrencyInstance(locale).format(123.45); // 123,45 DM locale = Locale.CANADA; string = NumberFormat.getCurrencyInstance(locale).format(123.45); // $123.45 13
// Parse try { Number number = NumberFormat.getCurrencyInstance(locale).parse("$123.45"); // 123.45 if (number instanceof Long) { // Long value else { // Double value catch (ParseException e) { 14
import java.text.dateformat; import java.util.date; public class Tarih02 { Tarih ve Saat Biçemleri public static void main(string[] args) { //Bir Date nesnesi kur. Şimdiki zamanı gösterir. Date now = new Date(); // tostring() metoduna tarihi yazdır System.out.println(" 1. " + now.tostring()); // Öntanımlı biçem: DateFormat System.out.println(" 2. " + DateFormat.getInstance().format(now)); // Öntanımlı tarih ve saat: DateFormats System.out.println(" 3. " + DateFormat.getTimeInstance().format(now)); System.out.println(" 4. " + DateFormat.getDateTimeInstance().format(now)); // Kısa, orta ve uzun DateFormat'ları: // Öntanımlıdırlar System.out.println(" 5. " + DateFormat.getTimeInstance(DateFormat.SHORT).format(now)); System.out.println(" 6. " + DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now)); System.out.println(" 7. " + DateFormat.getTimeInstance(DateFormat.LONG).format(now)); // Öntanımlı tarih ve saat biçemlerini belirleme: System.out.println(" 8. " + DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT).format(now)); System.out.println(" 9. " + DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.SHORT).format(now)); System.out.println("10. " + DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG).format(now)); 1. Sun Sep 12 22:42:17 EEST 2010 2. 12.09.2010 22:42 3. 22:42:17 4. 12.Eyl.2010 22:42:17 5. 22:42 6. 22:42:17 7. 22:42:17 EEST 8. 12.09.2010 22:42 9. 12.Eyl.2010 22:42 10. 12 Eylül 2010 Pazar 22:42:17 EEST 15