Converting string to an int

hi,
is there anyway i can easily convert a string into a long int.
I have an id string which consists of 11 characters, the first 3 are used to identify the type. the last 8 are numbers that need to go in a sequence.
Eg, 44400000001, next would be 44400000002 and so on.
i can break the string into two, but when i convert the last part into an int it does not keep the 0s. i need the length of this int to remain 8.
thanks
Shazan
Edited by: shazan on Apr 24, 2008 11:27 AM

shazan wrote:
...but when i convert the last part into an int it does not keep the 0s. i need the length of this int to remain 8.
How do you mean, keep the zeros?
int is short for integer, it doesn't have length as in number of characters...
What about keeping the last part as String as well and converting it inside the calculations (or whatever you're doing)... or maybe convert it and do what you're doing and then convert it back to String with padded zeros?

Similar Messages

  • Converting String type to inte type

    Can any one tell me how I can convert an array of Strings into an array of integers??

    it's simple ..... it's like this...
       // some code goes here....
       String num[]={"23", "342", "21", "1"};
        int n[]= new int[num.length];
        for(int i=0; i<num.length; i++)
             n=Integer.parseInt(num[i]); // << -- convert string to int then copied it to int[]
    // rest of your code....

  • How to convert String array into int.

    void getSoldSms(Vector vecSoldSms)
         String str[]=new String[vecSoldSms.size()];
         String words[]=new String[str.length]; // String array
              for(int i=0;i< vecSoldSms.size();i++)
                   str=(String)vecSoldSms.get(i);
              }               //End for
              for(int i=0;i<str.length;i++)
              words = str[i].split("\\|\\|");
              System.out.println();
              for(int j=0;j<1;j++)     
              int count[str.length]=Integer.parseInt(words[i]);
              System.out.print(count[j]*advance_count);
              } // end inner for loop
              }          //End for
         }          //End function getSoldSms
    how do i convert words which is a string array into int type. i kno string can be converted into int using interger.parseint. but wat abt string arrays??? plz help me out with the above code.

    i did tht its still giving the same errorFor Heaven's sake, what about taking a second to try to understand the code you're copying first? If you really can't fix the error yourself, you have a more serious problem than just convertingStrings to ints.
    And if you want { "1", "2", "3" } to be 123:
    StringBuffer b = new StringBuffer();
    for (int i = 0; i < array.length; i++) {
      b.append(array);
    int result = Integer.parseIn(b.toString());

  • How can I convert a String into an int?

    I need to use command-line args. So I enter "java Main 123" and I want to use 123 not as a String but as an int.
    How can I convert it into an int?
    Thank You!!
    Sprocket

    Example method (you don't need to use a method unless you do this a lot)
    private int stringTOInt (String aString)
    int result = 0;
    try
    result = Integer.parseString(aString);
    catch (Exception ex)
    System.out.println ("Failed to convert string " + aString + " to int.");
    return result;
    }

  • Converting string to int

    I cannot convert this string to integer.
    int tempI = Integer.parseInt("fdcedfbd", 16);
    it returns a numberFormatException
    but if I do this then there will be no problem.
    int tempI = 0xfdcedfbd
    Can anybody help me with this? Thank you.

    It sounds like the real problem here is that someone is giving you an 8-byte unsigned value represented as a 16-character hexadecimal string, and they want you to convert that into the actual 8 bytes. Are they going to do bit manipulation on it or something?
    If you successfully convert it into a long and they then try to do math with it, they'll run into the sign/overflow problems everyone else has been talking about. If they just want to look at the individual bits then it would make sense to do the conversion into a long.
    You could do something like this:
      private static final String highOrderDigits = "89abcdef";
      public long hexToLong(String hex) {
        // Only process exactly 16-digit strings.
        if (hex.length() != 16) {
          throw new IllegalArgumentException("Expect 16-digit hex value");
        boolean overflow = false;
        // Check for most significant digit > 7, which would
        // cause problem for parseLong.
        int highOrderIndex = highOrderDigits.indexOf(hex.charAt(0));
        if (highOrderIndex > -1) {
          // Clear most-significant bit and set overflow flag.
          overflow = true;
          hex = "" + highOrderIndex + hex.substring(1);
        long result = Long.parseLong(hex, 16);
        if (overflow) {
          // Manually set most significant bit in result.
          result |= 0x8000000000000000L;
        return result;
      }I more or less tested this and it looks to work.

  • 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?

  • Converting a String to an Int????  (Java)

    I am reading in a value from the user as a string. But I need to use that value as an int value. Can you parse a string to an int? Or can someone tell me another way I should be doing this?
    Thanks

    Integer.parseInt()
    Next time, search the forum, this gets asked every day.

  • Converting String to integer?

    I looked on the sun forums and only found a lot of things that convert integers to Strings. Nothing to do the opposite.
    Does anyone know how I can convert a String to an int?

    coopkev2 wrote:
    an "A" from a "B"?? I don't understand what you are saying... I want to convert "100" to 100.
    Edit-- I'll be back soon.Read "A" as "Integer" and "B" as "String".
    In this case: read the [java.lang.Integer API|http://java.sun.com/javase/6/docs/api/java/lang/Integer.html] if there is a method which takes a String and returns an Integer or int.

  • How to convert string to an integer in SQL Server 2008

    Hi All,
    How to convert string to an integer in sql server,
    Input : string str="1,2,3,5"
    Output would be : 1,2,3,5
    Thanks in advance.
    Regards,
    Sunil

    No, you cannot convert to INT and get 1,2,3 BUT you can get
    1
    2
    3
    Is it ok?
    CREATE FUNCTION [dbo].[SplitString]
             @str VARCHAR(MAX)
        RETURNS @ret TABLE (token VARCHAR(MAX))
         AS
         BEGIN
        DECLARE @x XML 
        SET @x = '<t>' + REPLACE(@str, ',', '</t><t>') + '</t>'
        INSERT INTO @ret
            SELECT x.i.value('.', 'VARCHAR(MAX)') AS token
            FROM @x.nodes('//t') x(i)
        RETURN
       END
    ----Usage
    SELECT * FROM SplitString ('1,2,3')
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Incompatible types - found java.lang.String but expected int

    This is an extremely small simple program but i keep getting an "incompatible types - found java.lang.String but expected int" error and dont understand why. Im still pretty new to Java so it might just be something stupid im over looking...
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Lab
    public static void main(String []args)
    int input = JOptionPane.showInputDialog("Input Decimal ");
    String bin = Integer.toBinaryString(input);
    String hex = Integer.toHexString(input);
    System.out.println("Decimal= " + input + '\n' + "Binary= " + bin + '\n' + "Hexadecimal " + hex);
    }

    You should always post the full, exact error message.
    Your error message probably says that the error occurred on something like line #10, the JOptionPane line. The error is telling you that the compiler found a String value, but an int value was expected.
    If you go to the API docs for JOptionPane, it will tell you what value type is returned for showInputDialog(). The value type is String. But you are trying to assign that value to an int. You can't do that.
    You will need to assign the showInputDialog() value to a String variable. Then use Integer.parseInt(the_string) to convert to an int value.

  • Converting string to xml Document object.

    Hi all,
    I having a string consiste of xml data.
    I wants to convert this to an xml document object.
    When i am trying to do this i am getting fatal error Premature End of file.
    This is sample code from my program.
    String xmlStr = " <TravelItineraryAddInfoRQ>
    <POS>
    <Source PseudoCityCode="A2PB"/>
    </POS>
    </TravelItineraryAddInfoRQ>";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware( false );
              DocumentBuilder builder = null;
              char[] ch = new char[1200];
    builder = factory.newDocumentBuilder();
    StringReader sr = new StringReader(xmlStr);
    InputSource is = new InputSource(sr);
    Reader r = is.getCharacterStream();
    r.read(ch);
    System.out.println("String Starting ==== ");
    for(int i=0;i<ch.length;i++)
    System.out.print(ch);
    Document XMLDoc = builder.parse(new InputSource(sr));
    System.out.println("Document Object ==== "+XMLDoc);
    thnx,
    raj

    Hi Rajaven,
    use the below step, I think it could help u
    StringBufferInputStream sb = new StringBufferInputStream(strBf));
    doc = db.parse(sb);first conver a string to StringBufferInputStream then parse to doc Object
    hope it will solve.
    let me know if it's not working
    With cheers,
    PrasannA

  • Memory leak in String(byte[] bytes, int offset, int length)

    Has anyone run into memory leak problem using this String(byte[] bytes, int offset, int length) class? I am using it to convert byte array to string, and I am showing memory leak using this class. Any idea what is going on?

    Hi,
    If you post in Native methods forum I assume you are using this constructor in the native side.
    Be aware that getting char * from jstring eats memory that you must free before returning from native with env->ReleaseStringUTFChars().
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Is there any native method for converting String value to Hungarian notat..

    Hello. there.
    This might be very simple question. but I'm just curious about this.
    I am wondering if Java API offer the any native method for converting uppercased string value to lowercase which obey the Hungarian notation.
    What I'm going to do is using Reflection for excuting RFC function on SAP. I was found it is very similar to JDBC Programming.
    Please refer to blow codes.
    //mTable
    JCoTable mTable = function.getTableParameterList().getTable(rtnTblNm);
        for (int i = 0; i < mTable.getNumRows(); i++) {
         mTable.setRow(i);
         HashMap tmpData = new HashMap ();
              for (int j=0; j < mTable.getNumColumns(); j++) {
                     // I want to set key String [userNo] instead of  [USER_NO] here.
              tmpData.put(mTable.getMetaData().getName(j).toLowerCase(), mTable.getString(j));
              result.add(tmpData);
    } Basically, The idea was from ibatis framework [com.ibatis.common.beans.classInfo] dropcase();
    Any idea would be very helpful for me. Thank you.
    Edited by: hosung.seo on Aug 30, 2009 10:42 PM
    Edited by: hosung.seo on Aug 30, 2009 10:50 PM

    ejp wrote:
    Hungarian notation is a representation of logical/arithmetic expressions in postfix form. Not what you're talking about.
    So your title is very confusing to the people here who know what it means, which is probably all of them, because people read threads based on their title.From now on, I will pay more attention when I post an question.
    If the titile as " +Is there any native method for converting String value to camelcase?"+ would be easier to what i'm pointing at.
    As I mentioned in above sorce code, converting [USER_NO] to [userNo] isn't relevant Hungarian notation. yes, it was ambiguous. Agree! :)
    But some answer wasn't fit to converting case or recognizing "underscore" delimiter. I was expecting toCamelCase() such as blew. Thanks.
        public static String toCamelCase(String name) {
            String lowerName = name.toLowerCase();
            String[] pieces = lowerName.split("_");
            if (pieces.length == 1) {
                return lowerName;
            StringBuffer result = new StringBuffer(pieces[0]);
            for (int i = 1; i < pieces.length; i++) {
                result.append(Character.toUpperCase(pieces.charAt(0)));
    result.append(pieces[i].substring(1));
    return result.toString();

  • Logic of converting strings to integer

    Hi all,
    I know that , I can convert a string into a number using API , Ineger.parseInt() . But i want to know the reall algoritham behind that
    .Can anybody explane that ?
    Basically I am interested in
      String s = "123";
      int i = Integer.parseInt(s);
      But i want to know what is the logic running behind this ?. Can anybody please help me. ...?
    Thanks in advance....

    The decompiled version parseInt() from Integer class
         * Parses the string argument as a signed decimal integer. The
         * characters in the string must all be decimal digits, except that
         * the first character may be an ASCII minus sign <code>'-'</code>
         * (<code>'&#92;u002D'</code>) to indicate a negative value. The resulting
         * integer value is returned, exactly as if the argument and the radix
         * 10 were given as arguments to the
         * {@link #parseInt(java.lang.String, int)} method.
         * @param s        a <code>String</code> containing the <code>int</code>
         *             representation to be parsed
         * @return     the integer value represented by the argument in decimal.
         * @exception  NumberFormatException  if the string does not contain a
         *               parsable integer.
        public static int parseInt(String s) throws NumberFormatException {
         return parseInt(s,10);
         * Parses the string argument as a signed integer in the radix
         * specified by the second argument. The characters in the string
         * must all be digits of the specified radix (as determined by
         * whether {@link java.lang.Character#digit(char, int)} returns a
         * nonnegative value), except that the first character may be an
         * ASCII minus sign <code>'-'</code> (<code>'&#92;u002D'</code>) to
         * indicate a negative value. The resulting integer value is returned.
         * <p>
         * An exception of type <code>NumberFormatException</code> is
         * thrown if any of the following situations occurs:
         * <ul>
         * <li>The first argument is <code>null</code> or is a string of
         * length zero.
         * <li>The radix is either smaller than
         * {@link java.lang.Character#MIN_RADIX} or
         * larger than {@link java.lang.Character#MAX_RADIX}.
         * <li>Any character of the string is not a digit of the specified
         * radix, except that the first character may be a minus sign
         * <code>'-'</code> (<code>'&#92;u002D'</code>) provided that the
         * string is longer than length 1.
         * <li>The value represented by the string is not a value of type
         * <code>int</code>.
         * </ul><p>
         * Examples:
         * <blockquote><pre>
         * parseInt("0", 10) returns 0
         * parseInt("473", 10) returns 473
         * parseInt("-0", 10) returns 0
         * parseInt("-FF", 16) returns -255
         * parseInt("1100110", 2) returns 102
         * parseInt("2147483647", 10) returns 2147483647
         * parseInt("-2147483648", 10) returns -2147483648
         * parseInt("2147483648", 10) throws a NumberFormatException
         * parseInt("99", 8) throws a NumberFormatException
         * parseInt("Kona", 10) throws a NumberFormatException
         * parseInt("Kona", 27) returns 411787
         * </pre></blockquote>
         * @param      s   the <code>String</code> containing the integer
         *                representation to be parsed
         * @param      radix   the radix to be used while parsing <code>s</code>.
         * @return     the integer represented by the string argument in the
         *             specified radix.
         * @exception  NumberFormatException if the <code>String</code>
         *              does not contain a parsable <code>int</code>.
        public static int parseInt(String s, int radix)
              throws NumberFormatException
            if (s == null) {
                throw new NumberFormatException("null");
         if (radix < Character.MIN_RADIX) {
             throw new NumberFormatException("radix " + radix +
                                 " less than Character.MIN_RADIX");
         if (radix > Character.MAX_RADIX) {
             throw new NumberFormatException("radix " + radix +
                                 " greater than Character.MAX_RADIX");
         int result = 0;
         boolean negative = false;
         int i = 0, max = s.length();
         int limit;
         int multmin;
         int digit;
         if (max > 0) {
             if (s.charAt(0) == '-') {
              negative = true;
              limit = Integer.MIN_VALUE;
              i++;
             } else {
              limit = -Integer.MAX_VALUE;
             multmin = limit / radix;
             if (i < max) {
              digit = Character.digit(s.charAt(i++),radix);
              if (digit < 0) {
                  throw NumberFormatException.forInputString(s);
              } else {
                  result = -digit;
             while (i < max) {
              // Accumulating negatively avoids surprises near MAX_VALUE
              digit = Character.digit(s.charAt(i++),radix);
              if (digit < 0) {
                  throw NumberFormatException.forInputString(s);
              if (result < multmin) {
                  throw NumberFormatException.forInputString(s);
              result *= radix;
              if (result < limit + digit) {
                  throw NumberFormatException.forInputString(s);
              result -= digit;
         } else {
             throw NumberFormatException.forInputString(s);
         if (negative) {
             if (i > 1) {
              return result;
             } else {     /* Only got "-" */
              throw NumberFormatException.forInputString(s);
         } else {
             return -result;
        }

  • Convert from char to int

    hey
    I've an input string ("1234")
    What i need to do is to fill a matrix 2*2 with the input string.
    I thought about running over the string, and by str.charAt(ind) to get a needed charters, but the question is ho do i convert charAt result to int?
    tanx

    igalep132 wrote:
    hey
    I've an input string ("1234")
    What i need to do is to fill a matrix 2*2 with the input string.
    I thought about running over the string, and by str.charAt(ind) to get a needed charters, but the question is ho do i convert charAt result to int?
    tanxThat's kinda vague. Do you mean convert '1' into the integer value 1 or convert '1' into the ASCII integer value of 49?
    Here's how to do the first:
    String one = "8";
    String two = "3";
    String numbers = "0123456789";
    int oneInt = numbers.indexOf(one);
    int twoInt = numbers.indexOf(two);
    System.out.println("oneInt = " + oneInt);
    System.out.println("twoInt = " + twoInt);If you meant the latter then ...
    char c = 'c';
    int cInt = (int)c;

Maybe you are looking for