Formatting an int value

I have an int ID which is a unique identifier within my code,
within lists I would like consecutive IDs to appear as 001,002, ... 009,010 etc
how do I go about adding preceding 0 placeholders to an int value?
The value must remain as an int, my specs do not permit me to parse it to a String value
I do remember coming across the methodology to perform this task a while back, but I cannot remember where I found it.
example:
int ID = 000; // initialize with '0' value, I want 3 places in the final value
ID = ++ID; // increment the ID within the constructor
System.out.print("ID = " + ID); // test the current value of ID
results in:
ID = 1
desired result would be
ID = 001
either direct 'How-To' or appropriate linkage would be appreciated

That was exactly what I had been looking for.
I knew I'd come across it when coding for a previous task, but for
the life of me I couldn't work out where <red face> I was missing
the "f" when I did my searches <doh>
I assume that if I then print the result to a file (with the preceding 0s)
that the placeholder 0s will be trimmed upon readback (as in my first
example), which will suit the specs of the task perfectly.
Many thanks

Similar Messages

  • Need help to convert this format of string in a int value?

    public static int isNumber( String number, int defaultValue ) {
              int result;
              try {
                   result = Integer.parseInt(number);
              } catch( Exception e ) {
                   result = defaultValue;
              return result;
         }Hi, I have the above method that converts a string Number into a int value. It works fine if the string is a normal number 234 (without spaces) but I have a string in the following format:
    *(space)�23,000(space).*
    That is I have a "space" then a "Pound" sign then two numbers then a comma followed by three numbers and then a space again.
    Is there any way I can convert this format into a simple int value?
    Thanks for any guidance.
    Zub

    Hi, I tried the following code but it don't seem to work
         public static int isNumberTrimSpaces( String number, int defaultValue ) {
              number.trim();
              String parsed = "";
              for (int i = 0 ; i < number.length() && number.charAt(i) != ',' ; i++)
             if (Character.isDigit(number.charAt(i))) {
             parsed += number.charAt(i);}
              int result;
              try {
                   result = Integer.parseInt(number);
              } catch( Exception e ) {
                   result = defaultValue;
              return result;
         }Any Ideas? Also will the loop get rid of the pound sign?

  • How to get Int value from request.getParameter()?

    Hi all,
    I have a integer value which is passed from one page to another page.
    i am geting this value in the next page using
    request.getParameter().
    Eg.
    Suppose value of "i" in page1 is 32, i pass this as hidden variable to next page.
    <input type="hidden" Value="<%=i%>" NAME="limit">
    in page2, i fethch this value to a variable by name "limit"
    String limit=request.getParameter("limit");
    but, since value stored in limit is int, i can't assign it to string.
    i can't use request.getParameter for int values.
    How to solve my problem.
    I know it is simple,
    Pls. help me
    Regards
    ASh
    String limit=request.getParameter("limit");

      String limitSTR = request.getParameter("limit");
      int limit = -1;
      if (limitSTR != null) limit = Integer.parseInt(limitSTR);

  • Format the total value in the column of the graph table

    Hello all,
    I have a graph table and I need to format the total value in the column of the table.
    I am trying to find my table bean with the code below but it's not working in the processRequest. Is there anything else that should be done?
    // Get the graph
    OAGraphTableBean graphBean = (OAGraphTableBean)webBean.findChildRecursive("MyGraph");
    // Get the table
    OATableBean tblBean = (OATableBean)graphBean.findChildRecursive("MyTable");
    The tblBean is null in the processRequest. In the processFormRequest the tblBean is not null.
    Thanks and Regards,
    Andrea

    Hi,
    The code OAGraphTableBean graphBean = (OAGraphTableBean)webBean.findChildRecursive("MyTable"); does not work because in this case I am getting the table but casting to a graph.
    The MyTable bean is a child of MyGraph.
    When creating a graph bean we have the option to create a table as a child (select your graphTable region in the Structure pane, and choose New > tabularFormat - to create the table).
    The table bean child I can get just in the processFormRequest, but the graph I can get in both processRequest and processFormRequest.
    I need to get the table bean in the processRequest to format the total value column.
    Do you know if is there anything else that should be done to format the total column?
    Thanks and Regards,
    Andrea

  • How to get int value from [session.getAttribute("String")]

    i am not able to get int value from the following statiment
    int i=session.getAttribute("String");
    i also try by casting it into int but it dont work, can somebody help me in this regard

    abuu wrote:
    i am not able to get int value from the following statiment
    int i=session.getAttribute("String");
    i also try by casting it into int but it dont work, can somebody help me in this regard
    Integer i=(Integer)session.getAttribute("String");
    i.intValue();but know how it is working. that is useful.
    Diablo.

  • Getting int values from a char array

    Hi,
    I need to make a fast program which reads lots of data from files and process them. I need to interpret these data as int's. To be more efficient and avoid to make a lot of disk access, I allocate in memory buffers part of the data, then process it and then allocate new data. The problem is that if I want to allocate data in memory buffers, all the methods that enables me to do that receceive as a parameter only a an array of chars, and as I have mentioned I need to interpret the data as a 4 bytes int. The static methods of Array to get the int value from a position ar not useful because the onlye get the int value of the indexed byte (or char); this method doesn't take 4 bytes from the index to build an int.
    My question is: is there any way to build an int from 4 bytes? or can I get the int's in this way directly from the buffer?
    Thank you,

    Isn't this one of the prime examples of using java.io.DataOutputStream and java.io.DataInputStream?

  • How do I know if I can convert a String value to an int value or not?

    Hi,
    I want to know how to make the judgment that if I can convert a String value to an int value or not? Assume that I don't know the String is number or letters
    Thank you

    Encephalopathic wrote
    Again, why?One of the problems (have been dued) in my codelab asks us to write a class as follow
    Write a class definition of a class named 'Value' with the following:
    a constructor accepting a single integer paramter
    a constructor with no parameters
    a method 'setVal' that accepts a single parameter,
    a boolean method, 'wasModified' that returns true if setVal was ever called for the object.
    a method 'getVal' that returns an integer value as follows: if setVal has ever been called, it getVal returns the last value passed to setVal. Otherwise if the "single int parameter" constructor was used to create the object, getVal returns the value passed to that constructor. Otherwise getVal returns 0.
    The setVal(int y) returns nothing, so how do I know whether it has been called or not?
    Thank you

  • Formatting the return value of: File(myFile).lastModified()

    I'm checking file date and time stamps:
    myDate = File(myFile).lastModified()Is there a way to format the return value?
    myDate equals: 1205166439145I'd like to see something like:
    03/10/2008  12:27 PMI'm using the following code to print the value:
    System.out.println(myDate);

    Awesome! I really, really appreciate the help and the sample code!
    Successful Output:
    K:\COMMON\ITS\STEVEB\java\CompareFileDates>java CompareFileDates
    execution continuing...
    test1.steve (3/10/08 12:27 PM) is older than test2.steve (3/10/08 1:33 PM)Error free code:
    import java.io.File;
    import java.lang.Object;
    import java.util.Date;
    import java.text.Format;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    public class CompareFileDates {
      public static void main(String[] args) {
        String file1_stat = null;
        String file2_stat = null;
        String file1 = "test1.steve";
        String file2 = "test2.steve";
        long date1 = 0;
        long date2 = 0;
        String finalDate1 = null;
        String finalDate2 = null;
        boolean file1Exists = (new File(file1)).exists();
        if (file1Exists) {
            // File or directory exists
            file1_stat = "does exist";
            // Get the timestamp from file 1 and format it
            date1 = (new File(file1)).lastModified();
         Date newDate1 = new Date(date1);
         DateFormat df = new SimpleDateFormat();
         finalDate1 = df.format(newDate1);
         //System.out.println(file1 + " date: " + finalDate1);
        else {
            // File or directory does not exist
            file1_stat = "does not exist";
        boolean file2Exists = (new File(file2)).exists();
        if (file2Exists) {
            // File or directory exists
            file2_stat = "does exist";
            // Get the timestamp from file 2 and format it
            date2 = (new File(file2)).lastModified();
         Date newDate2 = new Date(date2);
         DateFormat df = new SimpleDateFormat();
         finalDate2 = df.format(newDate2);
         //System.out.println(file2 + " date: " + finalDate2);
        else {
            // File or directory does not exist
            file2_stat = "does not exist";
        if ((file1Exists == false) || (file2Exists == false)) {
                System.out.println("aborting program...");
        else { 
           System.out.println("execution continuing...");
           String relation;
           if (date1 == date2)
             relation = "the same age as";
           else if (date1 < date2)
             relation = "older than";
           else
             relation = "newer than";
           System.out.println(file1 + " (" + finalDate1 + ")" + " is " + relation + ' ' + file2 + " (" + finalDate2 + ")");
    }

  • Comparing a single int to more than one int value?

    Hi is there a way to compare a single int value amongst several ints in one go?
    i know i could do if statements that can compare each int one by one but i was wondering if there is an easier way? like comparing all values amognst eachother
    somthing like
    int i;
    int a,b,c,d,e,f,,g;
    //ints a-g assigned some random numbers
    if(i == a,b,c,d,e,f,g)
          //do somthing here
    }

    i found out a way. i tried this way by using nested for loops and an if statement that compares every single value amongst eachother
    for(int q=0; q < 5; q++)
                ran[q] = (int)(java.lang.Math.random()*52);
            for(int x = 0; x < 5;x++)
                for(int z = 0; z < 5; z++)
                    if(x != z && ran[x] == ran[z])
                        ran[x] = (int)(java.lang.Math.random()*52);
            }

  • Mapping a key string to the KeyEvent int value

    /** Returns the int value of a key
    * @param the String representing the key. example "SHIFT" for the shift key
    * @return KeyEvent.VK_keyName
    public static int mapKeyCode(String keyName) {
    // we don't have access to an instance of KeyEvent!!!
    Class.forName("java.awt.event.KeyEvent").getDeclaredField("VK_"+keyName).getInt(obj..@#@#@
    //+ exception handling
    }

    public int keyTyped( KeyEvent event ) {
      try {
         return java.lang.Integer( String.valueOf( event.getKeyChar() ) );
      } catch ( NumberFormatException nfe ) {
         System.err.println( "NumberFormatException: " + nfe.getMessage() );
         return( 0 );
    }

  • In fact it's about mac:excel, how convert in a cell a number written in text format into a value?

    in fact it's about mac:excel8 or 11 in OSX10.7.4,
    how convert in a cell a number written in text format into its value?
    cheers francois

    Hi francois,
    If I copyone of them and do a past special/value, it does not work.
    Try just Paste instead of Paste Special > Value
    I know your question is about Excel, but this works in Numbers:
    Copy 1 234 567 (with spaces) and Paste (not Paste Special) into a Cell in a Numbers Table. The result is 1234567 and it behaves as a number. A formula will consider it to be a number:
    You asked Wayne: what do you mean by "to reference a cell" ??
    The reference is from Cell A2 to Cell A1 through a formula, such as: =A1+1
    Regards,
    Ian.

  • How to change double i = Math.random(); value to (int) value

    I am trying to find out how to convert a given double value to integer, which is, to conver double myNumber = Math.random() to (int) value. Here is the sample program look like this.
    Thank you for the help.
    import javax.swing.JOptionPane;
    public class numbers
    public static void main(String[] args)
    int upperLimit = Integer.parseInt(JOptionPane.showInputDialog
    (null, "Enter the upper range integer."));
    double myNumber = Math.random();
    //Test of Random numbers.
    System.out.println("The Upper random number limit is: " +
    myNumber * upperLimit);
    } //End of main.
    } // End of class.

    Not sure exactly what you want and why you want to change the double to an int. I'm assuming by this you want to generate random integers, from 1 to the upper limit the user enters? If so, this is how I would do it:import java.util.*;
    import javax.swing.*;
    public class Numbers
        public static void main(String[] args)
            int upperLimit = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the upper range integer."));
            Random r = new Random();
            int myNumber = r.nextInt(upperLimit) + 1;
            System.out.println(myNumber);
    }

  • Keeping track of an int value when server is stooped

    Hi
    In my JSP custom tag I have an int value which is used to keep track of the number of people that have visited the site. If the server was to be stopped or if it crashes is there any way where the int value can be stored and retrieved when the server starts up again? I am using tomcat but am reluctant to write to a text file whenever the int value is incremented for efficiency purposes. IF the server is stopped would there be any possible ways to store the number (it would be ok to write to text file just before stopping of tomcat happens).
    Thx
    Bal

    yes....
    you can do using context listeners....
    in the start of context listeners read from the file and add to context ... and when the context becomes inactive write to a file....
    for that you should use tomcat4.01 ... cause only tat has servlet 2.3 implementaion.
    if you are not using tat .. write to the file every 10 minutes .. atleast you will have the latest update of the counts when something crashes......................

  • Break formatting and number format of SUM value

    Where can I put number formatting functio, which will format breaking sum values...like:
    to_char(#SUM_VALUE#,'fmt 999G999G999G990')....maybe this thread is somewhere posted, but I cannot find it.
    Next, how to exclude showing reports total at the end of report?
    Is there any working demo to see some hints...
    THX!
    Message was edited by:
    Funky

    Hello Damir,
    "Maybe a hint for feature releases to have an option to disable total report sum on column …"There is a relative simple workaround, which will allow you exclude or highlight (style) this total report sum line, as you can see in here - http://htmldb.oracle.com/pls/otn/f?p=22710:10
    In the Report Attribute page, I'm using the Break Formatting section first field "Display this text when printing report sums" - http://i10.tinypic.com/4ie8ck5.png .
    If you want to exclude this line, you should use the same color as your cell background. For the example page, the code is looking like this:
    <div id="FinalSum"><script type="text/javascript">var lastRow=html_CascadeUpTill('FinalSum','TR'); lastRow.style.color='#f7f7e7';</script></div>If, on the other hand, you want to highlight the line, or use any other CSS attribute style available, the code would look something like this:
    <div id="FinalSum1"><script type="text/javascript">var lastRow=html_CascadeUpTill('FinalSum1','TR'); lastRow.style.backgroundColor='#CCCC99';</script>Total Report Sum</div>    Regards,
    Arie.

  • Can't read int value

    import java.io.*;
    class binary
         public static void main(String args[])
              BufferedReader br;
              int ch=0;
              br = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("enter value");
              try    
                   ch = (int)br.read();
              catch(IOException e)
                   System.out.println("Exception Caught");
              System.out.println("the value entered is :" +  ch);
    }the read method used above reads an character and returns it integer value and if we want to read an integer value how to do so, i tried it in the above code but it doesn't work
    is there any specific function for reading int values or we need to use the ByteStream classes instead of the Character ones
    plz reply

    thanks it worked
    i read my number using the readLine() method as a
    String and then converted it back to an int value
    ut is there no method by which i could read values as
    int from the console n not have to do the conversion
    part.plz heply guys

Maybe you are looking for