Role of FieldPosition in Format class?

I am learning about Format class, but I don't understand FieldPosition class which is used in format() method and ParsePosition() which is used in parseObject() method.
Can someone explain me their use?

import java.text.*;
import java.util.*;
public class BobMil{
  public static void main(String[] args){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    Date d = new Date();
    System.out.println(d.toString());
    System.out.println(sdf.format(d));
    StringBuffer sb = new StringBuffer();
    FieldPosition fp = new FieldPosition(DateFormat.Field.MINUTE);
    sdf.format(d, sb, fp);
    System.out.println("minute = " + getField(sb, fp));
    System.out.println("-----");
    String text = "abcd2007 08 29 10:11:25xyz";
    ParsePosition pp = new ParsePosition(text.indexOf("2007"));
    Date dn = sdf.parse(text, pp);
    System.out.println(dn.toString());
    System.out.println("remaining text = " + text.substring(pp.getIndex()));
  static String getField(StringBuffer buf, FieldPosition pos){
    return buf.substring(pos.getBeginIndex(), pos.getEndIndex());
}

Similar Messages

  • Is there any String format class available in J2ME?

    Hello,
    I am looking for a Formating class which should format a string. For example ( This is Java SE code):
    int num = 999;
                String str = " is my lucky number.";
                String s = String.Format("The Number : %d %s", num, str);I could not find any formatter class nor any direct api from String/StringBuffer class to format a string.
    Any suggestion on this is highly appreciated.
    Thank You.
    Regards,
    DK

    sojourner_jdk wrote:
    Hi DarrylBurke,
    You are right. Its not "Format". String has "format" function ..
    String s = String.format("The Number : %d %s", num, str);Is there such class/api in J2ME?
    Thanks,
    Regards,
    -DKIn J2ME MIDP, [String has no "format" function|http://java.sun.com/javame/reference/apis/jsr118/java/lang/String.html|javadoc].

  • Rounding to 2 decimal places WITHOUT using any formatting class

    Hello
    I'm trying to round a number (double) to 2 decimal places without using any of the formatting class like (DecimalFormat or Math.Round and BigDecimal). Is it possible to do it by just using typecast?

    OP:
    BigDecimal is not a formatting class. Math.round isn't a class at all.
    Typecasting doesn't really do that sort of thing at all (unless you count dropping fractional components when casting to an integer type).
    double holds values in binary format, so it's basically impossible to round to decimal values meaningfully.
    Chuck:
    I thought that BigDecimal supported arbitrary decimal precision, so one doesn't have to do that sort of thing....?

  • After Login Business roles are getting diffrent format

    Dear Experts,
            After upgrading when i am login  getting business roles with different format like one business role is divided into 3 to 4 lines but i want that only horizontal
    means in single line.
    Any help really appreciated.
    Thanks & Regards,
    Laxman

    Hi Dhimant,
    Business roles are splits like below fromat
    select business role :
                                    . sales
                                     organisation
                                    . service
                                      organisation
                                    . marketing
                                      organisation
    like this my business roles are coming but i want that  names in single line
    . select business role
                         sales  organisation
                         service  organisation
                         marketing organisation
    Thanks,
    Laxman

  • Security roles in a hierarchy format

    Hello,
    I have a requirement where I would like to put the security reporting roles in a group.  Now I have all my security reporting roles like a list.  Whereas I would like have them in a group.  I would appreciate your help.
    Current:
    FI Performance reports
    FI Balance sheet reports
    FI AR reports
    SD Sales performance reprots
    SD Sales reports
    SD Marketing reports;
    Expected:
    FI Reports
      --- KPI's
              --- FI Performance reports
      --- Financial
              --- FI Balance sheet reports
    SD Reports
       --- KPI's
              ---  SD Performance Reprots
       ---  Marketing Reports
    Thanks
    Vasun

    Nobody uses the LDAP roles in a portlet? Anybody knows other thread discussing similar issue (I can't find anything)?

  • Project role and staffing in formation

    Hi,
    As we kwon, we can not assign project definition responsible role for task.
    Is it standard functionality?
    For Example:
    Project Definition                        Responsible role as Project Lead.
         Phase_1                                 Responsible role  as Design Lead
             --> Task_design_1               Responsible role as Design Engender   
              --> Task design2             Responsible role as Project Lead
    Please Guide me for the same or any help link or any sap note on that will be great help.
    Thanks

    Hi,
    We are facing the problem with resource tab page.
    When User Click the resource tab page
    Runtime Errors         UNCAUGHT_EXCEPTION
    Exception              CX_DPR_FATAL_ERROR
    with the Exception error
    "Invalid parameters were transferred when calling"
    We notice that the problem is happen because "Role is assigned to a task that is directly assigned to the project Definition"
    We test it also, it works without any run time error.
    We just want information that it is standard Functionality or not with some SAP Document to prove this.
    Thanks

  • Correcting a bug in the JRE classes

    I have run across a bug in the class java.text.DecimalFormat
    I am using JSE 1.3.1_04, Windows XP professional o.s.
    The bug resides in the following method:
    public StringBuffer format(double number, StringBuffer
    result, FieldPosition fieldPosition)
    The following line of code within the abovementioned
    method will produce a "hotspot divide by zero error",
    if the variable named "number" contains a value of zero.
    boolean isNegative = (number < 0.0) || (number == 0.0 &&
    1/number < 0.0);
    I would like to repair this bug "in place" (actually change the line of code in error), and return the fixed class to the java.text package. How can I do this? I have extracted the source from the src.jar file, made the change, and now I need to replace the older version of this class.
    BTW, I have submitted a bug report, however, I cannot wait for the fix.

    Anyways, here is my somewhat "hacked" version of DecimalFormat.java to bypass the problem. Just make sure the following program resides in a directory that precedes the "rt.jar" file in the classpath.
    import java.text.FieldPosition;
    * A convenenience class to override the default implementation of DecimalFormat.
    * This is purely a "workaround" to avoid the "divide by zero" error that is occasionally
    * issued by the HotSpot  compiler.  See #format(double value) method for details
    * When (and if) there is a problem resolution in a future release, this program should be disabled
    * @author Stuart Leonard
    * @version 1.0
    * @since 09/08/2002
    class DecimalFormat
        private java.text.DecimalFormat decfmt;
        private String dft = "";
        private static final char       PATTERN_DIGIT              = '#';
         * The public constructor for this class.  Accepts a pattern to be used
         * by a java.text.DecimalFormat object
         * @param fmt The pattern to be used
        public DecimalFormat(String fmt)
            decfmt = new java.text.DecimalFormat(fmt);
            // check to see if last position of pattern is zero
            // if so, initialize a "zero balance" default pattern.
            if (fmt != null && fmt.length() > 0)
                StringBuffer strbuf = new StringBuffer(fmt);
                int endPos = strbuf.length()-1;
                if (strbuf.charAt(endPos) == '0')
                    int begPos = endPos;
                    for (int i = endPos; i>0; i--)
                        char chr = strbuf.charAt(i);
                        if (chr == PATTERN_DIGIT)
                            begPos = i+1;
                            break;
                    dft = strbuf.substring(begPos, endPos+1);
         * An overridden implementation of #java.text.NumberFormat.format(double)
         * If value is zero, then initialize return value with a blank suppressed
         * "zero balance" value, as specified by the original format pattern.
         * @param value The incoming double value to be formatted by a string pattern
         * @return The incoming value represented as a string pattern
        public String format (double value)
            String formatted = dft;
            if (value != 0)
                formatted = decfmt.format(value);
            return formatted;   
         * An overridden implementation of #java.text.DecimalFormat.format(double, StringBuffer, FieldPosition)
         * If value is zero, then initialize return value with a blank suppressed
         * "zero balance" value, as specified by the original format pattern.
         * Formats a double to produce a string.
         * @param number    The double to format
         * @param toAppendTo    where the text is to be appended
         * @param fieldPosition    On input: an alignment field, if desired.
         * On output: the offsets of the alignment field.
         * @return The value passed in as the result parameter
         * @see java.text.FieldPosition
        public StringBuffer format(double number, StringBuffer result,
                                   FieldPosition fieldPosition)
            StringBuffer strbuf = new StringBuffer();
            if (number != 0)
                strbuf = decfmt.format(number, result, fieldPosition);
            else   
                strbuf.append(dft);
            return strbuf;   
         * The default implementation of #java.text.NumberFormat.format(long)
         * This exists ONLY because of the "divide by zero" error that
         * is being issued by #java.text.DecimalFormat.format(double, String Buffer, FieldPosition)
         * @param value The incoming value to be formatted by a string pattern
         * @return The incoming value represented as a string pattern
        public String format (long value)
              return decfmt.format(value);
         * The default implementation of #java.text.DecimalFormat.format(long, StringBuffer, FieldPosition)
         * This exists ONLY because of the "divide by zero" error that
         * is being issued by #java.text.DecimalFormat.format(double, String Buffer, FieldPosition)
         * Format a long to produce a string.
         * @param number    The long to format
         * @param toAppendTo    where the text is to be appended
         * @param fieldPosition    On input: an alignment field, if desired.
         * On output: the offsets of the alignment field.
         * @return The value passed in as the result parameter
         * @see java.text.FieldPosition
        public StringBuffer format(long number, StringBuffer result,
                                   FieldPosition fieldPosition)
            return decfmt.format(number, result, fieldPosition);

  • OIM11gR2 Searching Role keys from role names

    Hi Experts,
    I have roles coming in String format "Role1,Role2,Role3",
    I want to fetch their role keys: I am using search criteria function as
    criteria = new SearchCriteria(RoleManagerConstants.ROLE_NAME,"Role1", SearchCriteria.Operator.EQUAL);
    attrNames.add(RoleManagerConstants.ROLE_KEY);
    roles = rmgr.search(criteria, attrNames, null);In the above code i have to iterate for each and every role one by one.
    Here if I want to use a single search criteria where i could pass this as a single string like
    criteria = new SearchCriteria(RoleManagerConstants.ROLE_NAME,"Role1,Role2,Role3", SearchCriteria.Operator.IN);Is it possible? I am trying with IN operator, but it is giving outofbound exception.
    Any Thougths?

    This code should resolve your issue
    private void SearchRoles(String RoleName1,String RoleName2,String RoleName3) {
    List<Role> roles = null;
    HashMap<String, Object> mapParams = null;
    Set<String> attrNames = null;
    RoleManager roleMgr = oimClient.getService(RoleManager.class);
    SearchCriteria searchCriteria = new SearchCriteria(RoleManagerConstants.ROLE_NAME, RoleName1, SearchCriteria.Operator.EQUAL);
    SearchCriteria searchCriteria1 = new SearchCriteria(RoleManagerConstants.ROLE_NAME, RoleName2, SearchCriteria.Operator.EQUAL);
    SearchCriteria searchCriteria2 = new SearchCriteria(searchCriteria, searchCriteria1, SearchCriteria.Operator.OR);
    SearchCriteria searchCriteria3 = new SearchCriteria(RoleManagerConstants.ROLE_NAME,RoleName3, SearchCriteria.Operator.EQUAL);
    SearchCriteria searchCriteria4 = new SearchCriteria(searchCriteria2,searchCriteria3, SearchCriteria.Operator.OR);
    try
    roles = roleMgr.search(searchCriteria4, attrNames, mapParams);
    System.out.println("Total Roles found:"+roles.size());
    for (Role role : roles)
    System.out.println(role.getEntityId()+":"+role.getName()+":"+role.getDisplayName()+":"+role.getNamespace());
    catch(Exception e) {
    e.printStackTrace();
    }

  • How to Change the default format for differnt language both in java and SQL

    Hello,
    I am using SQL Anywhere in my application.And in my java client application user can log in with their preferred language like English,French,German,Chinese,etc....When even the user log in to the application the data from the database will be displayed with respective to the language.But when i tried to see the dates in Interactive SQL all the dates r in the format of '2008-12-5 16:44:10:673' but say for example for Chinese it will be displayed as '08-12-5 16.44.10' and for some other language it will come in some other format(which is standard format for those language).
    Mean while i am using java client.When ever i am displaying a date it will be with respective to the language using Locale and date format classes.When i am displaying the date for Chinese in GUI it will show the date as '08-12-5 &#19979;&#21320;4:44'. In summary
    1. For Chinese,the default date pattern from SQL Anywhere date base is '08-12-5 16.44.10'
    2. For the same language date using java code is displaying as '08-12-5 &#19979;&#21320;4:44'. and i am getting the time format pattern as 'ah:mm'.I tried to change the display format in regional settings but no change in display.
    Is there any way to make both the time format as same?
    Please help me to solve this issue!!!
    Thanks in Advance!
    Arun

    pon_arun wrote:
    Hello masijade,
    I did as u said but still the date display is not the same......And I'm telling you that it doesn't matter. What "format" the DB likes to display a Date in when it displays it, is completely irrelevant to how you display it in your GUI.
    A Date does not have a format. A String representation of a Date does.
    As long as you use getDate from ResultSet and setDate from PreparedStatement you do not have to worry about this. Those methods will handle dates to and from the DB themselves. You can then use SimpleDateFormat to display the Date anyway you want to.
    Just because you show the Date one way, and the DB shows it another, does not mean that it is not the same date. Don't get hung up on how the String representation of the Date looks.
    Edit: If you simply want to be able to do "Human Comparisons" then look at the SQL TO_CHAR function (for Oracle, for other DBs the function name may vary). And for Java, read the API docs for SimpleDateFormat (as already intimated above).

  • Decimal Format and Scientific Notation

    I am trying to print numbers in scientific notation using the Decimal Format class. What follows is a simple test program I wrote to find the bug. So far, I have not found a solution.
    import java.text.*;
    public class formatted {
    public static void main (String Arguments[]) {
    DecimalFormat form = new DecimalFormat("0.###E0");
         double numb = 123456.789;
         System.out.println("Nuber is: " +
    form.format(numb));
    The output of this program is... Nuber is: 123456E
    The output is the same if numb is an int, float, or double. If I format the number as "#####.0" or "#####.00" the output is correct. I think that I am following the rules for formatting a number in scientific notation as the process is outlined in the documentation (provided below).
    ***** From Decimal Format under Scientific Notation ***
    Numbers in scientific notation are expressed as the product of a mantissa and a power of ten, for
    example, 1234 can be expressed as 1.234 x 10^3. The mantissa is often in the range 1.0 <= x < 10.0,
    but it need not be. DecimalFormat can be instructed to format and parse scientific notation only via a
    pattern; there is currently no factory method that creates a scientific notation format. In a pattern,
    the exponent character immediately followed by one or more digit characters indicates scientific
    notation. Example: "0.###E0" formats the number 1234 as "1.234E3".
    Anyone understand how the short program is incorrectly written?
    Marc

    The problem is
    format = "0.###E0"
    input number = 123456.789
    output = 123456E (not scientific notation!)
    This is not scientific notation at all. There is no decimal point given and no value in the exponent.
    I understand entirely that by adding more #'es will provide more precision. The bug I have is the output is not printed in the scientific format; other formats work.
    MArc

  • How to use function of an abstract class??

    Hi all,
    I want to use the format(object obj) function of the package java.text.Format. But as the Format class is an abstract class i could not instantiate it, so that i can call the format(object obj) method using the dot(.) operator.
    I know what is an abstract class. i've studied and tried to understand. as everybody knows, studied the perfect example(because i've read it in all the abstract class tutorial, books) of the Shape class. But still i dont understand how am i going to use that format(object obj) method. Please help me..

    Instead of using the abstract class Format use the
    concrete classes DecimalFormat
    SimpleDateFormat etc check java.text APIS
    http://java.sun.com/j2se/1.4.2/docs/api
    Hi!! Thanks both of you.
    If Sun has a abstract class then there must be a
    concrete class which extends that abstract class .It
    is always better to check the APIWhat do you mean by this line. Is it true for all the abstract classes in the jdk?

  • KEYNOTE: Why change the format of the presentations? not respect the original format!

    Why change the format of the presentations? Keynote not respect the original format!
    This new versionof Keynot (6.1-1769) is very poor:
    is very slow
    missing fonts
    changes the selected letters
    change the formats of the presentations
    Carousel animations missing
    Please correct the defects before releasing a new version. (The previous version was much better).

    Found the solution!
    I must set the Formats in the CODEC to get the Format that I want to play with! I was trying to complicate too much!
    The correct format class to is RGBFormat.
    RGB

  • Java formatting (This case occur only EVEN NUMBERS)

    This case only occur EVEN NUMBERS)
    I am using java number format class for formatting data. I have a double value 222.325 and I will be going to formatting this value. Formatting pattern is (#.00) after formatting final result is not getting 222.33,but I am getting 222.32.
    We have test cases:
    But similar cases I have a double value 222.335 after I am getting correct result 222.34
    I have a 222.315 after formatting I am getting 222.32.
    I have given my code below. Please advise me
    Is this java formatting class error or my code error pleased correct? ASAP
    see below example:
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    double d2 = 222.325;
    df.applyPattern("#.00");
    DecimalFormat df =
    (DecimalFormat)NumberFormat.getInstance();
    System.out.println("d2..."+df.format(d2));

    Please explain:
    - Why you had to spawn a new thread,
    - Where the behaviour of the code does not match [url http://forum.java.sun.com/thread.jspa?threadID=685964]Annie's description.

  • Java Formating (As soon as posible)

    I am using java number format class for formatting data. I have a double value 222.325 and I will be going to formatting this value. Formatting pattern is (#.00) after formatting final result is not getting 222.33,but I am getting 222.32.
    We have test cases:
    But similar cases I have a double value 222.335 after I am getting correct result 222.34
    I have a 222.315 after formatting I am getting 222.32.
    I have given my code below. Please advise me
    Is this java formatting class error or my code error pleased correct? ASAP
    see below example:
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    double d2 = 222.325;
    df.applyPattern("#.00");
    DecimalFormat df =
         (DecimalFormat)NumberFormat.getInstance();
    System.out.println("d2..."+df.format(d2));

    From the API:
    DecimalFormat</code> uses half-even rounding (see {@link java.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting.Also, in general, please be aware of:
    What Every Computer Scientist Should Know About Floating-Point Arithmetic
    http://docs.sun.com/source/806-3568/ncg_goldberg.html

  • How do i change my quicktime player default back to quicktime 7 as my new quicktime won't play  certain formats

    how do i change my quicktime player default back to quicktime 7 as my new quicktime won't play  certain formats

    Select one of those files, CMD+I, select QT 7 from the Open With list, and then click the Change All button. Repeat for any in the format class you want to change.

Maybe you are looking for

  • Using powershell to move a sub-site tree to a new site collection

    I have a case where I may need to move a subsite tree from one site collection to another existing site collection. The information I have normally seen on the web talks about creating a new site collection when moving a subsite tree. If I am going t

  • EXPORT_MD_TO_FILE

    Hello All, I am trying to run the standard EXPORT_MD_TO_FILE Data Manager Package. I'm having an issue with any descriptions that have a comma. If the description has a comma, it splits it into another column in the export. Thus, if I have: ID       

  • How to rename seller name in iTunes connect

    HI, In app Store we see that App Name and exactly below that seller name i.e. the name of individual or company name how to rename this name in itunes store?

  • Ports on various servers GRC, RWD, Loadrunner, Quality Center

    Y'all, With Governance, Risk, and Compliance on a Windows 2008 server, what ports should be open? Same for RWD, HP Loadrunner, and HP Quality Center. The port numbers, please. This is some hard to find info.  I've searched the Forums.  Not that it's

  • Kleine Fragen zu 5.0.2

    Hallo, bin recht begeistert, aber ein paar kleine Fragen sind schon noch: a. Kann es auch identische Bilder finden? Habe leider ein paar tausend doppelt :-( b. Kann ich nur direkt bei Kodak Bilder bestellen? (Ist ja leider nicht der günstigste :-( )