免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3177 | 回复: 4
打印 上一主题 下一主题

分享:java中的格式化输出(类似C语言的printf) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2003-08-09 11:04 |只看该作者 |倒序浏览
前几天想在java中用格式化输出,多亏rollingpig、zlzj2010等几位老大提示,现在我用text package中的NumberFormat和DecimalFomat实现了一把,给大家show一下,请多指教。

简单说明:

a.格式描述符:

1. L或l - 使数字左对齐(缺省是右对齐)
2. C或c - 使数字居中对齐(缺省是右对齐)
3. X或x - 显示数字为十六进制(缺省是十进制)
4. B或b - 显示数字为八进制(缺省是十进制)
5. ,(半角逗号)- 千位分隔符
6. S或s - 显示数字为科学记数法
7. Z或z - 用零填空位(缺省是空格)
8. w.d (两个整数用半角句号隔开)- 指定输出域宽及精度

b. "fillChar"是填空位符(缺省为空格)
--你可以用MyOut.fillChar = '*'或'$'来定义你自己的空位符


举例:
println(123.45678, "8.3L" ->; 123.457(左对齐占八位)
println(123.45678, "10.3cs" ->;  1.235E2 (居中占十位)
println(1234567, ",10" ->;   1,234,567(右对齐占十位)


// class MyOut

   
  1. import java.io.PrintStream;
  2. import java.io.PrintWriter;
  3. import java.io.OutputStreamWriter;
  4. import java.text.DecimalFormat;
  5. import java.text.NumberFormat;

  6. /* Thanks to Prof. H.Roumani.(He is my java teacher, who is great.)
  7. *
  8. * The format methods receive the value to be formatted (which can
  9. * be of any type) and a format descriptor: a string that contains
  10. * one or more of the following flags in any order and in any case:
  11. *
  12. * L:
  13. *   By default, all values are aligned right within their field
  14. *   width. If this flag is specified, left alignment is used instead.
  15. *   This flag has no effect if the field width is not specified.
  16. * C:
  17. *   By default, all values are aligned right within their field
  18. *   width. If this flag is specified, centre alignment is used instead.
  19. *   This flag has no effect if the field width is not specified.
  20. * X:
  21. *   By default, all numeric values are shown in the decimal system.
  22. *   If this flag is specified, hexadecimal is used instead (showing
  23. *   IEEE-754 for real's). This flag has no effect if the value is not
  24. *   numeric.
  25. * B:
  26. *   By default, all numeric values are shown in the decimal system.
  27. *   If this flag is specified, binary is used instead (showing
  28. *   IEEE-754 for real's). This flag has no effect if the value is not
  29. *   numeric.
  30. * ,:
  31. *   By default, all numeric, base-10 values are shown without a
  32. *   thousand-separator. If this flag is specified, a comma is inserted
  33. *   in the integer part of the number to separate thousands. This flag
  34. *   has no effect if the value is not numeric, is not in decimal, or if
  35. *   the scientific notation is used.
  36. * S:
  37. *   By default, all numeric, base-10 values are shown as an integer part
  38. *   followed by a mantissa, or fractional part. If this flag is specified,
  39. *   scientific notation is used: One digits (possibly preceded by a minus
  40. *   sign) followed by a decimal point, a mantissa, the letter 'E' and an
  41. *   exponent. This flag has no effect if the value is not numeric or is not
  42. *   in decimal.
  43. * Z:
  44. *   By default, all integer, base-10 values are shown with leading or
  45. *   trailing spaces to fill the specified field width. If this flag is
  46. *   specified, the field is filled with leading zeros instead. This flag is
  47. *   only meaningful if the value is a base-10 integer, the width is specified,
  48. *   and the thousand-separator flag is not specified.
  49. * w.d (two integers separated by a period):
  50. *   w is the desired width of the entire returned string, after formatting.
  51. *   If the formatted string is shorter than w, it will be padded by leading
  52. *   and/or trailing spaces (or some other fill character) depending on the
  53. *   requested alignment (left, right, or centre). d is the desired number of
  54. *   decimals and is meaningful only if the value is a base-10 real (in standard
  55. *   or scientific notation). Rounding to the specified number of decimals is
  56. *   done using conventional rules but the case of 5 is handled by rounding to
  57. *   the nearest even number (same as the rint method of the Math class). Note
  58. *   that you can specify only w (in that case don't include the period), or
  59. *   only d (in this last case do precede it by the period).
  60. */

  61. public class MyOut
  62. {
  63.     /*************************************************************
  64.      Formats the passed value using the passed format descriptor
  65.      and returns the result as a string.
  66.    
  67.      @param value the value to be formatted.
  68.      @param fd the format descriptor.
  69.      @return the formatted value as a string.
  70.     **************************************************************/
  71.     public static String format(byte value, String fd)
  72.     {
  73.         return formatInteger(value, fd, 8);
  74.     }

  75.     /*************************************************************
  76.      Formats the passed value using the passed format descriptor
  77.      and returns the result as a string.
  78.    
  79.      @param value the value to be formatted.
  80.      @param fd the format descriptor.
  81.      @return the formatted value as a string.
  82.     **************************************************************/   
  83.     public static String format(char value, String fd)
  84.     {
  85.         return formatInteger(value, fd, 16);
  86.     }

  87.     /*************************************************************
  88.      Formats the passed value using the passed format descriptor
  89.      and returns the result as a string.
  90.    
  91.      @param value the value to be formatted.
  92.      @param fd the format descriptor.
  93.      @return the formatted value as a string.
  94.     **************************************************************/   
  95.     public static String format(double value, String fd)
  96.     {
  97.         extractAttributes(fd);
  98.         String s1;
  99.         if(base == 'B')
  100.         {
  101.             s1 = Long.toBinaryString(Double.doubleToLongBits(value));
  102.             s1 = repeat(64, '0') + s1;
  103.             s1 = s1.substring(s1.length() - 64);
  104.         } else if(base == 'X')
  105.         {
  106.             s1 = Long.toHexString(Double.doubleToLongBits(value));
  107.             s1 = repeat(16, '0') + s1;
  108.             s1 = s1.substring(s1.length() - 16);
  109.         } else
  110.         {
  111.             pattern = decimals != -1 ? "." + repeat(decimals, '0') : ".#";
  112.             if(scientific)
  113.                 pattern = "0" + pattern + "E0";
  114.             else
  115.                 pattern = separator ? "#,##0" + pattern : "0" + pattern;
  116.             s1 = (new DecimalFormat(pattern)).format(value);
  117.         }
  118.         return size(s1);
  119.     }

  120.     /*************************************************************
  121.      Formats the passed value using the passed format descriptor
  122.      and returns the result as a string.
  123.    
  124.      @param value the value to be formatted.
  125.      @param fd the format descriptor.
  126.      @return the formatted value as a string.
  127.     **************************************************************/   
  128.     public static String format(float value, String fd)
  129.     {
  130.         extractAttributes(fd);
  131.         String s1;
  132.         if(base == 'B')
  133.         {
  134.             s1 = Integer.toBinaryString(Float.floatToIntBits(value));
  135.             s1 = repeat(32, '0') + s1;
  136.             s1 = s1.substring(s1.length() - 32);
  137.         } else if(base == 'X')
  138.         {
  139.             s1 = Integer.toHexString(Float.floatToIntBits(value));
  140.             s1 = repeat(8, '0') + s1;
  141.             s1 = s1.substring(s1.length() - 8);
  142.         } else
  143.         {
  144.             pattern = decimals != -1 ? "." + repeat(decimals, '0') : ".#";
  145.             if(scientific)
  146.                 pattern = "0" + pattern + "E0";
  147.             else
  148.                 pattern = separator ? "#,##0" + pattern : "0" + pattern;
  149.             s1 = (new DecimalFormat(pattern)).format(value);
  150.         }
  151.         return size(s1);
  152.     }

  153.     /*************************************************************
  154.      Formats the passed value using the passed format descriptor
  155.      and returns the result as a string.
  156.    
  157.      @param value the value to be formatted.
  158.      @param fd the format descriptor.
  159.      @return the formatted value as a string.
  160.     **************************************************************/   
  161.     public static String format(int value, String fd)
  162.     {
  163.         return formatInteger(value, fd, 32);
  164.     }

  165.     /*************************************************************
  166.      Formats the passed value using the passed format descriptor
  167.      and returns the result as a string.
  168.    
  169.      @param value the value to be formatted.
  170.      @param fd the format descriptor.
  171.      @return the formatted value as a string.
  172.     **************************************************************/   
  173.     public static String format(long value, String fd)
  174.     {
  175.         return formatInteger(value, fd, 64);
  176.     }
  177.    
  178.     /*************************************************************
  179.      Formats the passed value using the passed format descriptor
  180.      and returns the result as a string.
  181.    
  182.      @param value the value to be formatted.
  183.      @param fd the format descriptor.
  184.      @return the formatted value as a string.
  185.     **************************************************************/   
  186.     public static String format(short value, String fd)
  187.     {
  188.         return formatInteger(value, fd, 16);
  189.     }
  190.    
  191.     /* Formats the passed value using the passed format descriptor
  192.      * and returns the result as a string.
  193.      */
  194.     private static String formatInteger(long l, String s, int i)
  195.     {
  196.         extractAttributes(s);
  197.         String s1;
  198.         if(base == 'B')
  199.         {
  200.             s1 = Long.toBinaryString(l);
  201.             s1 = repeat(64, '0') + s1;
  202.             s1 = s1.substring(s1.length() - i);
  203.         } else
  204.         if(base == 'X')
  205.         {
  206.             s1 = Long.toHexString(l);
  207.             s1 = repeat(16, '0') + s1;
  208.             s1 = s1.substring(s1.length() - i / 4);
  209.         } else
  210.         if(separator)
  211.         {
  212.             s1 = (new DecimalFormat("#,###")).format(l);
  213.         } else
  214.         {
  215.             s1 = String.valueOf(l);
  216.             if(zeroFill)
  217.                 s1 = repeat(width - s1.length(), '0') + s1;
  218.         }
  219.         return size(s1);
  220.     }

  221.     // Gets information from the passed format descriptor.
  222.     private static void extractAttributes(String s)
  223.     {
  224.         s = s.toUpperCase();
  225.         alignment = 'R';
  226.         separator = false;
  227.         base = 'D';
  228.         scientific = false;
  229.         zeroFill = false;
  230.         width = -1;
  231.         decimals = -1;
  232.         int i = s.indexOf(76, 0);
  233.         if(i >; -1)
  234.         {
  235.             alignment = 'L';
  236.             s = s.substring(0, i) + s.substring(i + 1);
  237.         }
  238.         i = s.indexOf(67, 0);
  239.         if(i >; -1)
  240.         {
  241.             alignment = 'C';
  242.             s = s.substring(0, i) + s.substring(i + 1);
  243.         }
  244.         i = s.indexOf(44, 0);
  245.         if(i >; -1)
  246.         {
  247.             separator = true;
  248.             pattern = pattern + ",###";
  249.             s = s.substring(0, i) + s.substring(i + 1);
  250.         }
  251.         i = s.indexOf(88, 0);
  252.         if(i >; -1)
  253.         {
  254.             base = 'X';
  255.             s = s.substring(0, i) + s.substring(i + 1);
  256.         } else
  257.         {
  258.             i = s.indexOf(66, 0);
  259.             if(i >; -1)
  260.             {
  261.                 base = 'B';
  262.                 s = s.substring(0, i) + s.substring(i + 1);
  263.             }
  264.         }
  265.         i = s.indexOf(83, 0);
  266.         if(i >; -1)
  267.         {
  268.             scientific = true;
  269.             s = s.substring(0, i) + s.substring(i + 1);
  270.         }
  271.         i = s.indexOf(90, 0);
  272.         if(i >; -1)
  273.         {
  274.             zeroFill = true;
  275.             s = s.substring(0, i) + s.substring(i + 1);
  276.         }
  277.         i = s.indexOf(46, 0);
  278.         if(i >; -1)
  279.         {
  280.             decimals = Integer.parseInt(s.substring(i + 1));
  281.             s = s.substring(0, i);
  282.         }
  283.         if(s.length() >; 0)
  284.             width = Integer.parseInt(s);
  285.     }
  286.         
  287.     /*************************************************************
  288.      Output the passed value to the standard output device using
  289.      the passed format descriptor. No trailing End-Of-Line
  290.      character is printed.
  291.    
  292.      @param value the value to be printed.
  293.      @param fd the format descriptor.
  294.     **************************************************************/   
  295.     public static void print(byte value, String fd)
  296.     {
  297.         handle.print(format(value, fd));
  298.         handle.flush();
  299.     }

  300.     /*************************************************************
  301.      Output the passed value to the standard output device using
  302.      the passed format descriptor. No trailing End-Of-Line
  303.      character is printed.
  304.    
  305.      @param value the value to be printed.
  306.      @param fd the format descriptor.
  307.     **************************************************************/     
  308.     public static void print(char value, String fd)
  309.     {
  310.         handle.print(format(value, fd));
  311.         handle.flush();
  312.     }

  313.     /*************************************************************
  314.      Output the passed value to the standard output device using
  315.      the passed format descriptor. No trailing End-Of-Line
  316.      character is printed.
  317.    
  318.      @param value the value to be printed.
  319.      @param fd the format descriptor.
  320.     **************************************************************/     
  321.     public static void print(double value, String fd)
  322.     {
  323.         handle.print(format(value, fd));
  324.         handle.flush();
  325.     }

  326.     /*************************************************************
  327.      Output the passed value to the standard output device using
  328.      the passed format descriptor. No trailing End-Of-Line
  329.      character is printed.
  330.    
  331.      @param value the value to be printed.
  332.      @param fd the format descriptor.
  333.     **************************************************************/     
  334.     public static void print(float value, String fd)
  335.     {
  336.         handle.print(format(value, fd));
  337.         handle.flush();
  338.     }

  339.     /*************************************************************
  340.      Output the passed value to the standard output device using
  341.      the passed format descriptor. No trailing End-Of-Line
  342.      character is printed.
  343.    
  344.      @param value the value to be printed.
  345.      @param fd the format descriptor.
  346.     **************************************************************/     
  347.     public static void print(int value, String fd)
  348.     {
  349.         handle.print(format(value, fd));
  350.         handle.flush();
  351.     }

  352.     /*************************************************************
  353.      Output the passed value to the standard output device using
  354.      the passed format descriptor. No trailing End-Of-Line
  355.      character is printed.
  356.    
  357.      @param value the value to be printed.
  358.      @param fd the format descriptor.
  359.     **************************************************************/     
  360.     public static void print(long value, String fd)
  361.     {
  362.         handle.print(format(value, fd));
  363.         handle.flush();
  364.     }
  365.    
  366.     /*************************************************************
  367.      Output the passed value to the standard output device using
  368.      the passed format descriptor. No trailing End-Of-Line
  369.      character is printed.
  370.    
  371.      @param value the value to be printed.
  372.      @param fd the format descriptor.
  373.     **************************************************************/     
  374.     public static void print(short value, String fd)
  375.     {
  376.         handle.print(format(value, fd));
  377.         handle.flush();
  378.     }
  379.    
  380.     /*************************************************************
  381.      Output the passed value to the standard output device using
  382.      the passed format descriptorand followed by an End-Of-Line
  383.      marker.
  384.    
  385.      @param value the value to be printed.
  386.      @param fd the format descriptor.
  387.     **************************************************************/     
  388.     public static void println(byte value, String fd)
  389.     {
  390.         print(value, fd);
  391.         handle.print(EOL);
  392.         handle.flush();
  393.     }

  394.     /*************************************************************
  395.      Output the passed value to the standard output device using
  396.      the passed format descriptorand followed by an End-Of-Line
  397.      marker.
  398.    
  399.      @param value the value to be printed.
  400.      @param fd the format descriptor.
  401.     **************************************************************/     
  402.     public static void println(char value, String fd)
  403.     {
  404.         print(value, fd);
  405.         handle.print(EOL);
  406.         handle.flush();
  407.     }

  408.     /*************************************************************
  409.      Output the passed value to the standard output device using
  410.      the passed format descriptorand followed by an End-Of-Line
  411.      marker.
  412.    
  413.      @param value the value to be printed.
  414.      @param fd the format descriptor.
  415.     **************************************************************/     
  416.     public static void println(double value, String fd)
  417.     {
  418.         print(value, fd);
  419.         handle.print(EOL);
  420.         handle.flush();
  421.     }

  422.     /*************************************************************
  423.      Output the passed value to the standard output device using
  424.      the passed format descriptorand followed by an End-Of-Line
  425.      marker.
  426.    
  427.      @param value the value to be printed.
  428.      @param fd the format descriptor.
  429.     **************************************************************/     
  430.     public static void println(float value, String fd)
  431.     {
  432.         print(value, fd);
  433.         handle.print(EOL);
  434.         handle.flush();
  435.     }

  436.     /*************************************************************
  437.      Output the passed value to the standard output device using
  438.      the passed format descriptorand followed by an End-Of-Line
  439.      marker.
  440.    
  441.      @param value the value to be printed.
  442.      @param fd the format descriptor.
  443.     **************************************************************/     
  444.     public static void println(int value, String fd)
  445.     {
  446.         print(value, fd);
  447.         handle.print(EOL);
  448.         handle.flush();
  449.     }

  450.     /*************************************************************
  451.      Output the passed value to the standard output device using
  452.      the passed format descriptorand followed by an End-Of-Line
  453.      marker.
  454.    
  455.      @param value the value to be printed.
  456.      @param fd the format descriptor.
  457.     **************************************************************/     
  458.     public static void println(long value, String fd)
  459.     {
  460.         print(value, fd);
  461.         handle.print(EOL);
  462.         handle.flush();
  463.     }

  464.     /*************************************************************
  465.      Output the passed value to the standard output device using
  466.      the passed format descriptorand followed by an End-Of-Line
  467.      marker.
  468.    
  469.      @param value the value to be printed.
  470.      @param fd the format descriptor.
  471.     **************************************************************/     
  472.     public static void println(short value, String fd)
  473.     {
  474.         print(value, fd);
  475.         handle.print(EOL);
  476.         handle.flush();
  477.     }
  478.    
  479.     // Returns the string padding with 'fillChar'.   
  480.     private static String size(String s)
  481.     {
  482.         int i = width - s.length();
  483.         if(alignment == 'R')
  484.             return repeat(i, fillChar) + s;
  485.         if(alignment == 'L')
  486.             return s + repeat(i, fillChar);
  487.         else
  488.             return repeat(i / 2, fillChar) + s + repeat(i / 2 + i % 2, fillChar);
  489.     }   
  490.    
  491.     // Repeats the passed character 'times' times.
  492.     public static String repeat(int times, char c)
  493.     {
  494.         String s = "";
  495.         for(int i = 0; i < times; i++)
  496.             s = s + c;

  497.         return s;
  498.     }
  499.    
  500.     private static final String EOL = System.getProperty("line.separator");
  501.     private static PrintWriter handle = new PrintWriter(new OutputStreamWriter(System.out));
  502.     public static char fillChar = ' ';
  503.     private static char alignment;
  504.     private static boolean separator;
  505.     private static char base;
  506.     private static boolean scientific;
  507.     private static boolean zeroFill;
  508.     private static int width;
  509.     private static int decimals;
  510.     private static String pattern;   
  511. }
复制代码


// class MyOutTester

  1. // Test the format of numbers in different ways.
  2. public class MyOutTester
  3. {
  4.    public static void main(String[] args)
  5.    {
  6.       int i = 230;
  7.       double d = 114.495678905;
  8.       
  9.       // Unformatted
  10.       System.out.print(i + " ");
  11.       System.out.println(d);
  12.       
  13.       // Some formatting
  14.       MyOut.print(i, "11");
  15.       MyOut.println(d, "14.3");
  16.       
  17.       // More formatting
  18.       MyOut.print(i, "11L");
  19.       MyOut.println(d, ",14.7");  
  20.       
  21.       // Scientific
  22.       MyOut.print(i, ",11");
  23.       MyOut.println(d, ",14.6s");
  24.       
  25.       // Hexdecimal
  26.       MyOut.print(i, "x11");
  27.       MyOut.println(d, "x21");
  28.       
  29.       // Changed fillChar
  30.       MyOut.fillChar = '*';
  31.       MyOut.print(i, "11");
  32.       MyOut.println(d, "14.3");
  33.       
  34.       // Special case
  35.       MyOut.println(d, "");
  36.    }
  37. }              
复制代码

论坛徽章:
0
2 [报告]
发表于 2003-08-09 11:06 |只看该作者

分享:java中的格式化输出(类似C语言的printf)

ScreenHunter_001.jpg (12.68 KB, 下载次数: 51)

执行结果

执行结果

论坛徽章:
0
3 [报告]
发表于 2003-08-09 11:59 |只看该作者

分享:java中的格式化输出(类似C语言的printf)

不错,小华真牛人!

论坛徽章:
0
4 [报告]
发表于 2003-08-09 12:02 |只看该作者

分享:java中的格式化输出(类似C语言的printf)

不错啊
有收获

论坛徽章:
0
5 [报告]
发表于 2003-08-11 11:36 |只看该作者

分享:java中的格式化输出(类似C语言的printf)

牛x
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP