⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 format.java

📁 Java2核心技术卷一 配套源码,看了还不错
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package corejava;

import java.io.*;

/**
   A class for formatting numbers that follows <tt>printf</tt> conventions.

   Also implements C-like <tt>atoi</tt> and <tt>atof</tt> functions
   
   @version 1.20 25 Mar 1998
   @author Cay Horstmann
 */

public class Format
{ /** 
     Formats the number following <tt>printf</tt> conventions.
     
     Main limitation: Can only handle one format parameter at a time
     Use multiple Format objects to format more than one number
     
     @param s the format string following printf conventions
        The string has a prefix, a format code and a suffix. The prefix and suffix
        become part of the formatted output. The format code directs the
        formatting of the (single) parameter to be formatted. The code has the
        following structure
        <ul>
        <li> a % (required)
        <li> a modifier (optional)
        <dl>
        <dt> + <dd> forces display of + for positive numbers
        <dt> 0 <dd> show leading zeroes
        <dt> - <dd> align left in the field
        <dt> space <dd> prepend a space in front of positive numbers
        <dt> # <dd> use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format.
        </dl>
        <li> an integer denoting field width (optional)
        <li> a period followed by an integer denoting precision (optional)
        <li> a format descriptor (required)
        <dl>
        <dt>f <dd> floating point number in fixed format
        <dt>e, E <dd> floating point number in exponential notation (scientific format). The E format results in an uppercase E for the exponent (1.14130E+003), the e format in a lowercase e.
        <dt>g, G <dd> floating point number in general format (fixed format for small numbers, exponential format for large numbers). Trailing zeroes are suppressed. The G format results in an uppercase E for the exponent (if any), the g format in a lowercase e.
        <dt>d, i <dd> integer in decimal
        <dt>x <dd> integer in hexadecimal
        <dt>o <dd> integer in octal
        <dt>s <dd> string
        <dt>c <dd> character
        </dl>
        </ul>
     @exception IllegalArgumentException if bad format
   */

   public Format(String s)
   {  width = 0;
      precision = -1;
      pre = "";
      post = "";
      leading_zeroes = false;
      show_plus = false;
      alternate = false;
      show_space = false;
      left_align = false;
      fmt = ' '; 
      
      int state = 0; 
      int length = s.length();
      int parse_state = 0; 
      // 0 = prefix, 1 = flags, 2 = width, 3 = precision,
      // 4 = format, 5 = end
      int i = 0;
      
      while (parse_state == 0)
      {  if (i >= length) parse_state = 5;
         else if (s.charAt(i) == '%')
         {  if (i < length - 1)
            {  if (s.charAt(i + 1) == '%')
               {  pre = pre + '%';
                  i++;
               }
               else
                  parse_state = 1;
            }
            else throw new java.lang.IllegalArgumentException();
         }
         else
            pre = pre + s.charAt(i);
         i++;
      }
      while (parse_state == 1)
      {  if (i >= length) parse_state = 5;
         else if (s.charAt(i) == ' ') show_space = true;
         else if (s.charAt(i) == '-') left_align = true; 
         else if (s.charAt(i) == '+') show_plus = true;
         else if (s.charAt(i) == '0') leading_zeroes = true;
         else if (s.charAt(i) == '#') alternate = true;
         else { parse_state = 2; i--; }
         i++;
      }      
      while (parse_state == 2)
      {  if (i >= length) parse_state = 5;
         else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
         {  width = width * 10 + s.charAt(i) - '0';
            i++;
         }
         else if (s.charAt(i) == '.')
         {  parse_state = 3;
            precision = 0;
            i++;
         }
         else 
            parse_state = 4;            
      }
      while (parse_state == 3)
      {  if (i >= length) parse_state = 5;
         else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
         {  precision = precision * 10 + s.charAt(i) - '0';
            i++;
         }
         else 
            parse_state = 4;                  
      }
      if (parse_state == 4) 
      {  if (i >= length) parse_state = 5;
         else fmt = s.charAt(i);
         i++;
      }
      if (i < length)
         post = s.substring(i, length);
   }      

  /** 
     prints a formatted number following printf conventions

     @param fmt the format string
     @param x the double to print
   */
  
   public static void printf(String fmt, double x)
   {  System.out.print(new Format(fmt).format(x));
   }

  /** 
     prints a formatted number following printf conventions

     @param fmt the format string
     @param x the int to print
   */

   public static void printf(String fmt, int x)
   {  System.out.print(new Format(fmt).format(x));
   }

  /** 
     prints a formatted number following printf conventions

     @param fmt the format string
     @param x the long to print
   */

  public static void printf(String fmt, long x)
   {  System.out.print(new Format(fmt).format(x));
   }

  /** 
     prints a formatted number following printf conventions

     @param fmt the format string
     @param x the character to print
   */
  
   public static void printf(String fmt, char x)
   {  System.out.print(new Format(fmt).format(x));
   }

  /** 
     prints a formatted number following printf conventions

     @param fmt the format string
     @param x a string to print
   */
  
   public static void printf(String fmt, String x)
   {  System.out.print(new Format(fmt).format(x));
   }

  /** 
     Converts a string of digits (decimal, octal or hex) to an integer

     @param s a string
     @return the numeric value of the prefix of s representing a base 10 integer
   */
  
   public static int atoi(String s)
   {  return (int)atol(s);
   } 
   
  /** 
     Converts a string of digits (decimal, octal or hex) to a long integer

     @param s a string
     @return the numeric value of the prefix of s representing a base 10 integer
   */
  
   public static long atol(String s)
   {  int i = 0;

      while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
      if (i < s.length() && s.charAt(i) == '0')
      {  if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X'))
            return parseLong(s.substring(i + 2), 16);
         else return parseLong(s, 8);
      }
      else return parseLong(s, 10);
   }

   private static long parseLong(String s, int base)
   {  int i = 0;
      int sign = 1;
      long r = 0;
      
      while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
      if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
      else if (i < s.length() && s.charAt(i) == '+') { i++; }
      while (i < s.length())
      {  char ch = s.charAt(i);
         if ('0' <= ch && ch < '0' + base)
            r = r * base + ch - '0';
         else if ('A' <= ch && ch < 'A' + base - 10)
            r = r * base + ch - 'A' + 10 ;
         else if ('a' <= ch && ch < 'a' + base - 10)
            r = r * base + ch - 'a' + 10 ;
         else 
            return r * sign;
         i++;
      }
      return r * sign;      
   }
      
   /** 
      Converts a string of digits to a <tt>double</tt>

      @param s a string
    */
   
   public static double atof(String s)
   {  int i = 0;
      int sign = 1;
      double r = 0; // integer part
      double f = 0; // fractional part
      double p = 1; // exponent of fractional part
      int state = 0; // 0 = int part, 1 = frac part
      
      while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
      if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
      else if (i < s.length() && s.charAt(i) == '+') { i++; }
      while (i < s.length())
      {  char ch = s.charAt(i);
         if ('0' <= ch && ch <= '9')
         {  if (state == 0)
               r = r * 10 + ch - '0';
            else if (state == 1)
            {  p = p / 10;
               r = r + p * (ch - '0');
            }
         }
         else if (ch == '.') 
         {  if (state == 0) state = 1; 
            else return sign * r;
         }
         else if (ch == 'e' || ch == 'E')
         {  long e = (int)parseLong(s.substring(i + 1), 10);
            return sign * r * Math.pow(10, e);
         }
         else return sign * r;
         i++;
      }
      return sign * r;
   }
            
   /** 
      Formats a <tt>double</tt> into a string (like sprintf in C)

      @param x the number to format
      @return the formatted string 
      @exception IllegalArgumentException if bad argument
    */
   
   public String format(double x)
   {  String r;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -