Parsing Strings to Int, NumberFormatException ??

Hey everyone...
I am trying to convert some string to an int value..
Now this is what is exactly happening.. First i read some bytes into an array of bytes from a file. Then i use the toString() to convert it to a string. Once i get the string representation of it i use Integer.parseInt() to convert it to int. Now here i get a NumberFormatException, and i guess i know why. The file that has the bytes to be read represents char as 8 bits and in Java char are 16 bits. So could that be the problem. And secondly, when i convert the bytes to string, should'nt it convert it to a 16 bit char ??? I've also tried to use radix like Integer.parseInt(String s, radix 16) yet it does'nt work.. Thanks in advance....

Thanks...
Another question, how do i represent an US-ASCII enoding in the constructor...??? What i mean is what do i put inside this new String(byte_array, - - - - -) if i want to do them as ASCII ???

Similar Messages

  • Checking a value...String OR int

    checking a value...String OR int
    how to check a given value whether it is a String OR int
    if(jTextField1.getText()...) is a String
         System.out.println("String");
    else //if it an int
         System.out.println("int");
    How can i check this...
    pls,tell.

    getText of JTextField ALWAYS returns a String.
    You can do this to see if it could be interpreted as an int:
    String theText = jTextField1.getText();
    try
       int theInt = Integer.parseInt(theText);
       System.out.println("int");
    catch (NumberFormatException ex)
       System.out.println("String");
    }If it isn't in a form that can be parsed as an int, you will get an exception and the catch block will get executed.

  • String to int conversion

    can n e body tell me how can i convert a String to an int

    always remember to use the try/catch block with thins that throw exceptions
    String gg;
    int in;
    try{  
    gg = "30";
       in = Integer.parseInt(gg);
    catch(NumberFormatException e){ 
      e.printStackTrace();
    }Ant

  • Please help me with my code (has conversion from string to int)

    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Test3 extends MIDlet implements CommandListener
    {   Form mForm;
        Command mCommandQuit;
        Command mCommandItem;
        TextField input,prime1,prime2,prime3,output;
        Display mDisplay;
        int i,j=0,k1,k2,p,q,b;
        //int [] current=new int [1000];
        String mstring,a="";
        String [] temp=new String [1000];
        public void startApp()
        {System.out.println("startApp");
         mForm=new Form("RSA Encryption");
         mCommandQuit=new Command("QUIT",Command.EXIT,0);
         mCommandItem=new Command("ENCRYPT",Command.ITEM,0);
         mForm.append("Enter text:\n");
         input=new TextField(null,"",100, TextField.ANY);
         mForm.append(input);
         mForm.append("Enter first prime number(p):\n");
         prime1=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime1);
         mForm.append("Enter second prime number(q):\n");
         prime2=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime2);
         mForm.append("Enter d:\n");
         prime3=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime3);
         mForm.addCommand(mCommandQuit);
         mForm.addCommand(mCommandItem);
         mDisplay=Display.getDisplay(this);
         mDisplay.setCurrent(mForm);
         mForm.setCommandListener(this);
        public void pauseApp()
        {System.out.println("pauseApp");
        public void destroyApp(boolean unconditional)
        {System.out.println("destroyApp");
        public void commandAction(Command c, Displayable d)
        {System.out.println("commandAction");
         if(c==mCommandQuit)
            notifyDestroyed();
         else if(c==mCommandItem)
         {p = Integer.parseInt(prime1.getString());
             q = Integer.parseInt(prime2.getString());
             b = Integer.parseInt(prime3.getString());
             //breaking up of big string into ints
             mstring=input.getString();
             temp[0]="";
             for(i=1;i<mstring.length();i++)
                {if (mstring.charAt(i) == ' ')
                    {j++;
                     temp[j]="";
                 else
                    {temp[j]=temp[j]+mstring.charAt(i);
             mForm.append("\n\nThe array is:\n");
             for(i=0;i<temp.length && temp!=null;i++)
    {k1=Integer.parseInt(temp[i]); ***********************
    k2=k1;
    for(j=1;j<b;j++)
    {k1=k1*k2;
    k1=k1 %(p*q);
    k2=k1 %(p*q);
    a=a+new Character((char)k2).toString();
    output=new TextField(null,a,100, TextField.ANY);
    mForm.append(output);
    }hi
    this code basically takes an input of string like " 179 84 48 48 155 " (with spaces)
    then it creates smaller strings in an array like "179","84","48","48","155" without the spaces
    then it creates int values 179,84,48,48,155 and finally after some math functions it prints the corresponding letters.
    the problem is that it is not printing the letter because of some exceptions-->java.lang.NumberFormatException .it comes in the line where i have put stars
    could anybody please help me print the letters                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    thanks for all ur help guys, but me and my team member solved it on our own. here is the new code:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Test3 extends MIDlet implements CommandListener
    {   Form mForm;
        Command mCommandQuit;
        Command mCommandItem;
        TextField input,prime1,prime2,prime3,output;
        Display mDisplay;
        int i,j=0,l,k1,k2,p,q,n,b;
        String mstring,a = "";
        String [] temp=new String [1000];
        public void startApp()
        {System.out.println("startApp");
         mForm=new Form("RSA Encryption");
         mCommandQuit=new Command("QUIT",Command.EXIT,0);
         mCommandItem=new Command("DECRYPT",Command.ITEM,0);
         mForm.append("Enter text:\n");
         input=new TextField(null,"",100, TextField.ANY);
         mForm.append(input);
         mForm.append("Enter first prime number(p):\n");
         prime1=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime1);
         mForm.append("Enter second prime number(q):\n");
         prime2=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime2);
         mForm.append("Enter d:\n");
         prime3=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime3);
         mForm.addCommand(mCommandQuit);
         mForm.addCommand(mCommandItem);
         mDisplay=Display.getDisplay(this);
         mDisplay.setCurrent(mForm);
         mForm.setCommandListener(this);
        public void pauseApp()
        {System.out.println("pauseApp");
        public void destroyApp(boolean unconditional)
        {System.out.println("destroyApp");
        public void commandAction(Command c, Displayable d)
        {System.out.println("commandAction");
         if(c==mCommandQuit)
            notifyDestroyed();
         else if(c==mCommandItem)
         {p = Integer.parseInt(prime1.getString());
             q = Integer.parseInt(prime2.getString());
             b = Integer.parseInt(prime3.getString());
             n=p*q;
             //breaking up of big string into ints
             mstring=input.getString();
             temp[0]="";
             for(i=1;i<mstring.length();i++)
                {if (mstring.charAt(i) == ' ')
                    {j++;
                     temp[j]="";
                 else
                    {temp[j]=temp[j]+mstring.charAt(i);
             l=j;
             mForm.append("\n\nThe result is:\n");
             for(i=0;i<l;i++)
                {k1=Integer.valueOf(temp).intValue();
    k2=k1;
    for(j=1;j<b;j++)
    {k2=k2*k1;
    k2=k2 %n;
    k1=k2 %n;
    a=a+new Character((char)k1).toString();
    output=new TextField(null,a,100, TextField.ANY);
    mForm.append(output);

  • How to parse string to date in j2me?

    How to parse string to date in j2me?
    Please help me.

    Hi..
    String dyStr = "20";
    String mtStr = "1";
    String yrStr = "1999";
    Calendar cal = Calendar.getIntstance();
    int dy = Integer.parseInt(dyStr);
    int mt = Integer.parseInt(mtStr);
    int yr = Integer.parseInt(yrStr);
    cal.set(Calendar.DATE, dy);
    cal.set(Calendar.MONTH, mt);
    cal.set(Calendar.YEAR, yr);
    OK?

  • How can i cast array of string to int ?

                       while(st.hasMoreTokens()){
                                  test[count] = st.nextToken();
                                  count++;
                          }Since token deal with string, i have to pass them into String of array, but how can i convert all of them to int to perform arithmetic operation?

         public static void main (String[] args) throws IOException{
               DataInputStream dis = null;
                 String dbRecord = null;
                 int tokenCount = 0;
                 int numOfQuestion = 0;
                 int questionnAireNum = 0;
                 int postCode = 0;
                 int age = 0;
                 int gender = 0;
                 String [] response = new String[10];
                    File f = new File("polldata.txt");
                    FileInputStream fis = new FileInputStream(f); 
                    BufferedInputStream bis = new BufferedInputStream(fis); 
                    dis = new DataInputStream(bis);
                    // read the first record of the database
                    while ( (dbRecord = dis.readLine()) != null) {
                       StringTokenizer st = new StringTokenizer(dbRecord, ",");
                       tokenCount = st.countTokens();
                       numOfQuestion = tokenCount-4;
                       String rquestionNum = st.nextToken();
                       questionnAireNum = Integer.parseInt(rquestionNum);
                       String rpostCode = st.nextToken();
                       postCode = Integer.parseInt(rpostCode);
                       String rAge  = st.nextToken();
                       age = Integer.parseInt(rAge);
                       String rGender = st.nextToken();
                       gender = Integer.parseInt(rGender);
                       for(int i=0; i<numOfQuestion;i++){
                            response[i] = st.nextToken();
                       }hi how come when i cast the string as int it prompt me error as shown below ? I wonder what causes this because this is normally how i cast string to int, somehow it won work this way with token.
    Exception in thread "main" java.lang.NumberFormatException: For input string: " 3"
         at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
         at java.lang.Integer.parseInt(Integer.java:447)
         at java.lang.Integer.valueOf(Integer.java:553)
         at test.main(test.java:43)

  • Getting back the parsed string

    Hello,
    I am using a tokenizer to parse a string. Can u tell me if there's any other way to get the original string without the delimiter?
    String sai = "Help, me";
    String newSai;
    StringTokenizer parser = new StringTokenizer(sai,",",false);
    Vector v1 = new Vector();
    while (parser.hasMoreTokens())
      v1.addElement(parser.nextToken());       
      for (int a=0; a<v1.size();a++)
        newSai = (newSai+(String)v1.get(a));Thanks

    I'm not sure if this is what you want, but
    this will get rid of the commas in the String:
    String strTest = "This, is, a, test!";
    String strAdjusted = strTest.replaceAll(",", "");
    Alpha75

  • How could i parse string and link its model with my files in eclipse project?

    How could i parse string and link its model with my files in eclipse project?, as i read that we dont have to use standalone mode while working with eclipse projects.
    Example of what i want to do:
    I have file1.dsl in my project which contains some statements but the declaration of these statements are not in another file, i need to put them only in my code

    Hi Stefan,
    I have eclipse project contains 2 files, file1.dsl and file2.dsl, you can see the contents of the files below.
    file1.dsl contains some statements as shown below and file2.dsl contains the declarations of the variables. (like in C++ or Java we have declarations and usage)
    At this step file1.dsl and file2.dsl will be parsed successfully without any errors.
    Lets imagine that we will delete this project and will create another one and the new project will contain only file1.dsl (which contains the usage)
    At this step this file (file1.dsl) will contains some errors after parsing it, because we are using variables without declarations.
    So what i need is to parse the content of file2.dsl directly without adding this file to the project.
    I need to add the content of file2.dsl directly as a string in the code and parse it. just like that ( "int a;int b;" )
    And link file1.dsl with the model generated after parsing my string
    file1.dsl
    a++;
    b++;
    file2.dsl
    int a;
    int b;
    Thanks

  • Split Function unable to parse string correctly

    Hi,
    I'm using split function to split string into multiple rows using comma "," as delimiter. In a string I have following values which are not parsed correctly as they have comma inside the values. 
    American Dawn, Inc.
    Battalian USA, Inc.
    Fria USA, Inc.
    Lazer, Inc.
    Mexilink Inc.
    Is there any other approach to fix this issue?
    Here is the split function Im using:
    CREATE Function [dbo].[fnSplit] (
    @List varchar(MAX), 
    @Delimiter char(1)
    Returns @Temp1 Table (
    ItemId int Identity(1, 1) NOT NULL PRIMARY KEY , 
    Item varchar(MAX) NULL 
    As 
    Begin 
    Declare @item varchar(MAX), 
    @iPos int 
    Set @Delimiter = ISNULL(@Delimiter, ';' ) 
    Set @List = RTrim(LTrim(@List)) 
    -- check for final delimiter 
    If Right( @List, 1 ) <> @Delimiter -- append final
    delimiter 
    Select @List = @List + @Delimiter -- get position of
    first element 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    While @iPos > 0 
    Begin 
    -- get item 
    Select @item = LTrim( RTrim( Substring( @List, 1, @iPos
    -1 ) ) ) 
    If @@ERROR <> 0 Break -- remove item form list 
    Select @List = Substring( @List, @iPos + 1, Len(@List)
    - @iPos + 1 ) 
    If @@ERROR <> 0 Break -- insert item 
    Insert @Temp1 Values( @item ) If @@ERROR <> 0 Break 
    -- get position pf next item 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    If @@ERROR <> 0 Break 
    End 
    Return 
    End
    Another user in this forum posted a split function that
    he wrote:
    CREATE FUNCTION dbo.splitter(@string VARCHAR(MAX), @delim CHAR(1))
    RETURNS @result TABLE (id INT IDENTITY, value VARCHAR(MAX))
    AS
    BEGIN
    WHILE CHARINDEX(@delim,@string) > 0
    BEGIN
    INSERT INTO @result (value) VALUES (LEFT(@string,CHARINDEX(@delim,@string)-1))
    SET @string = RIGHT(@string,LEN(@string)-CHARINDEX(@delim,@string))
    END
    INSERT INTO @result (value) VALUES (@string)
    RETURN
    END
    GO
    Both of them are unable to parse above values incorrectly.
    FYI:  String is made of values that are selected
    by user in SSRS report. I think SSRS when combine values , put comma "," between multiple values.
    Any help or guidance would be appreciated.
    ZK

    duplicate of
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/820ac53c-ce25-4cc7-b828-5875a21d459d/split-function-unable-to-parse-string-correctly-in-ssrs-report?forum=sqlreportingservices
    please dont cross post
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • String into int & vice versa

    Hi all
    i cant convert the String into int although using
    Integer.parseInt & vice versa
    any ideas
    here is the code
    // fontCB & styleCB & sizeCB are ComboBoxes
    String fontName,fontStyle,fontSize;
    int fontStyleInt=1,fontSizeInt=1;
    fontName                = (String)fontCB.getSelectedItem();
    fontStyle               = (String)styleCB.getSelectedItem();
    fontSize               = (String)sizeCB.getSelectedItem();
    try
    fontStyleInt      = Integer.parseInt(fontStyle);
    fontSizeInt      = Integer.parseInt(fontSize);
    catch (NumberFormatException nfe)
    System.out.println("I'm an error");
    Font fontTemp           = new Font(fontName,fontStyleInt,fontSizeInt);
    myTextArea.setFont(fontTemp);

    The getSelectedItem() method returns a type called "Object". Therefore, to convert it to a string, u have to use String.valueOf(fontCB.getSelectedItem);Font styles are integers, i.e. PLAIN=0, BOLD=1, ITALIC=2, BOLD & ITALIC =3
    So, u can do the following,
    String styles={"Plain","Bold","Italics","Bold and Italics"};
    styleCB=new JComboBox(styles);To get the appropriate style, all u have to do is:
    int style=styleCB.getSelectedIndex();As for the font size,
    int size=Integer.parseInt(String.valueOf(sizeCB.getSelectedItem()));I think u r having plans for a text editor. right?

  • String to Int and Int to String

    How can I convert a string to Int & and an Int to String ?
    Say I've
    String abc="234"
    and I want the "int" value of "abc", how do I do it ?
    Pl. help.

    String.valueOf(int) takes an int and returns a string.
    Integer.parseInt(str) takes a string, returns an int.
    For all the others long, double, hex etc. RTFM :)

  • How to read a C structure with string and int with a java server using sock

    I ve made a C agent returning some information and I want to get them with my java server. I ve settled communication with connected socket but I m only able to read strings.
    I want to know how can I read strings and int with the same stream because they are sent at the same time:
    C pgm sent structure :
    char* chaine1;
    char* chaine2;
    int nb1;
    int nb2;
    I want to read this with my java stream I know readline methode to get the first two string but after two readline how should I do to get the two int values ?
    Any idea would be a good help...
    thanks.
    Nicolas (France)

    Does the server sent the ints in little endian or big endian format?
    The class java.io.DataInputStream (with the method readInt()) can be used to read ints as binary from the stream - see if you can use it.

  • Parsing String

    i have problem to parse string to document
    i have string like this str = "<root><data>1</data><data>2</data><root>";
    how to parse this string in docoment xml

    import java.io.*;
    import org.jdom.*;
    import org.jdom.input.*;
    import org.jdom.output.*;
    public class PrettyPrinter {
       public static void main(String[] args) {
            // Assume filename argument
            String filename = args[0];
            try {
                // Build the document with SAX and Xerces, no validation
                SAXBuilder builder = new SAXBuilder();
                // Create the document
                Document doc = builder.build(new File(filename));
                // Output the document, use standard formatter
                XMLOutputter fmt = new XMLOutputter();
                fmt.output(doc, System.out);
            } catch (Exception e) {
                e.printStackTrace();
    }The above code is taken directly from
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0518-jdom-p2.html
    u don't have to use Factories, this is what is said in that excerpt, it is very easy to use, and it is said that 80 % of the xml work can be done with 20 % or less work using JDOM.
    n joy ....
    </ksenji>

  • How to convert String to int in JSP?

    Hi,
    I set a session attribute in Servlet and want use it in JSP, How can I convert it to int or Integer?
    the line in my code doesn't work:
    int quantity=(int)session.getAttribute("vehiclequantity") ;
    Thanks in advance.
    Wolf
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    <HTML>
    <HEAD>
    <TITLE>Using the for Statement</TITLE>
    </HEAD>
    <BODY>
    <H1>Using the for Statement</H1>
    <%=session.getAttribute("vehiclequantity") %>;
    <%
    int loopIndex;
    int quantity=(int)session.getAttribute("vehiclequantity") ;
    out.println(quantity);
    for (loopIndex = 1; loopIndex <=2; loopIndex++) {
    out.println("This is iteration number "
    + loopIndex + "<BR>");
    %>
    </BODY>
    </HTML>

    Learning how to read errors and understand them will help you solve your problems quicker by yourself... So lets take a look at the error and classes involved...
    The error says:
    "Cannor Resolve Symbol: method valueOf(java.lang.Object) in the class java.lang.Integer" and gives you line line where the error occurs: Integer quantity = Integer.valueOf(session.getAttribute("vehiclequantity"));
    Now, if we look at the API for the Integer we notice that are are only two valueOf methods: valueOf(java.lang.String s) and valueOf(java.lang.String s, int radix). Not valueOf(java.lang.Object) method.
    Now we look at the getAttribute(java.lang.String name) method of HttpSession we see that the method returns a java.lang.Object. Now, you know you put a java.lang.String into that attribute, but the get method returns an Object. This is because you could have put any object in there, an Integer, a String, or some other class instance. But you know it is a String, so you can cast the returned value to a String, so that you will be calling the valueOf(java.lang.String s) method of Integer with the Object returned from the HtttpSession's getAttribute(java.lang.String name) method:
    Integer quantity = Integer.valueOf((String)session.getAttribute("vehiclequantity"));

  • Kinda urgent    please help pass strings to doubles and strings to ints

    Need to know how to pass strings to doubles and strings to ints
    and to check if a string is null its just if (name == null;) which means black right?
    like size as a string and then make the string size a double

    cupofjava666 wrote:
    Need to know how to pass strings to doubles and strings to ints
    and to check if a string is null its just if (name == null;) which means black right?
    like size as a string and then make the string size a doubleThink he means blank.
    Check the Wrapper classes (Double, Integer) in the api.
    parseInt() parseDouble() both take a string and return a primitive.
    String s = null;
    if(s == null) should do the trick!
    Regards.
    Edited by: Boeing-737 on May 29, 2008 11:08 AM

Maybe you are looking for