Convert from String to Int

Hi,
I have a question.
How do I convert from String to Integer?
Here is my code:
try{
String s="000111010101001101101010";
int q=Integer.parseInt(s);
answerStr = String.valueOf(q);
catch (NumberFormatException e)
answerStr="Error";
but, everytime when i run the code, i always get the ERROR.
is the value that i got, cannot be converted to int?
i've done the same thing in c, and its working fine.
thanks..

6kyAngel wrote:
actually it convert the string value into decimal value.In fact what it does is convert the (binary) string into an integer value. It's the String representation of integer quantities that have a base (two, ten, hex etc): the quantities themselves don't have a base.
To take an integer quantity (in the form of an int) and convert it to a binary String, use the handy toString() method in the Integer class - like your other conversion, use the one that takes a radix argument.

Similar Messages

  • Leading Zeroes are lost when convert from string to int

    What I'm trying to do is simple yet the solution has seemed difficult to find.
    I have a system that requires 4 digit numbers as "requisitionNo". The system uses JSPs and accepts the 4 digit number that the user inputs (fyi - duplicate handling is already managed). The input number (rNumber) is of STRING type and in the action (using struts) is converted to an int:
    int requisitionNo = Integer.parseInt(rNumber);At that very line the issue is that when the user inputs a number with leading zeros such as: "0001" the 3 leading zeros are chopped off in the INT conversion. The application validation kicks in and says: "A 4 digit number is required" which is by design. The work around has been that the user has been putting in number that start with 9's or something like that, but this isn't how the system was intended to be used.
    How do I keep the leading zeroes from being lost instead of saving a number "1" to the database how do I keep it saving "0001" to the database? Would I just change everything to STRING on down to the database? or is there another number type that I can be using that will not chop off the leading zeroes? Please provide short code references or examples to be more helpful.

    Yeah, I have to agree here that leading zeroes make no sense. I figured that out when I started to look into this problem. The only requirement that exists is that the user wants it to be a 4 digit number due to some other requirement they have themselves.
    So what I'm gathering from what I've read in the responses thus far is that I should change the validation a bit to look at the STRING for the 4 required digits (which are really 4 characters; maybe I should add CLIENT side numeric validation; currently its doing server side numeric/integer validation; or maybe change up the server side validation instead???) and if they are ALL GOOD then let the application save the int type as it wants to. IE: Let it save "0001" as just "1" and when I come back to DISPLAY this saved number to the user I should append the string of "000" in front of the 1 for display purposes only? Am I understanding everyone correctly?

  • Convert from String to HashMap

    Hi
    Can any body pls tell us how to convert from String to HashMap
    I have one string str="Col1=200, Col2=225";
    So how can i convert that string varibale into HashMap?

    Hi
    Can any body pls tell us how to convert from String
    to HashMap
    I have one string str="Col1=200, Col2=225";
    So how can i convert that string varibale into
    HashMap?
    Map map = new HashMap();
    String[] parts = str.split(", ");
    for (int i = 0; i < parts.length; ++i) {
        String[] entry = parts.split("=");
    map.put(entry[0], entry[1]);

  • Convert from String data type to Character data type

    Hi...,
    I'm a beginner. I try to make a program. But I don't know how to convert from string to data type. I try to make a calculator with GUI window. And when somebody put "+" to one of the window, I just want to convert it to Character instead of String.
    Sorry of my bad english..
    Please help me....
    Thanks

    String s = "a+b";
    char theplus = s.charAt(1);

  • Convert from String to boolean ??

    hi everyone..
    is there any way to convert from String (as a class) to boolean (as a primitive type) ?
    thunx

    I used : Boolean.valueOf(s).booleanValue(); ,I got the same error.What same error? Surely not this one:
    cannot resolve simple in parseBoolean method??
    equals is OK, but I think it is not convert method,
    the prev. solutions by equals don't convert the value of s (String).Yes it does, for any reasonable definition of "converts". In fact, that is essentially how parseBoolean() is implemented. From the JDK 5.0 source code, class java.lang.Boolean:
         return ((name != null) && name.equalsIgnoreCase("true"));

  • Convert from String to Long

    Hello Frineds I want to convert from String to Long.
    My String is like str="600 700 250 300" and I want to convert it to long and
    get the total value in to the long variable.like the total of str in long varible should be 1850.
    Thank You
    Nilesh Vasani

    Maybe this would work?
    StringTokenizer st = new StringTokenizer(yourString, " ");
    long l = 0;
    while(st.hasMoreTokens()) {
        l += Long.parseLong(st.nextToken()).longValue();
    }

  • Convert from String to float

    How do I convert from String to float?

    Hi,
    you can use a Double for example - assuming value is that string to parse
    float f;
    try { Double d = new Double(value); f = d.floatValue(); }
    catch (NumberFormatException e) { f = 0.0; } // error - string value could not be parsed
    // here use your float fHope, that helps
    greetings Marsian
    P.S.: the Double class is usefull for that, because you also can get intValue(), doubleValue() or longValue() out of it for example. The StreamTokenizer for example parses numbers also only to double.

  • Date Formatting, Converting from String to Timestamp

    I am trying to convert a string date to timestamp.
    I have tried a couple of different ways to arrive at the end result.
    I am basically trying to convert a date in the "dd-MM-yyyy" format to a timestamp.
    If I use the following code, I get a date like this "18-May-2004 12:00:00 AM".
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy);
    Date dContractDate = sdf.parse("18-05-2004");
    long dateInMilli = dContractDate.getTime();
    bHelp.bcontractdate = new Timestamp(dateInMilli);
    How can I make this code display the current time not midnight or some defaulted value?
    Thanks.

    I think a clever person would reuse their Date.classObject and call Date.setTime() as opposed to always
    rolling out a new Date()
    Not really a question of cleverness. Your code wins
    nothing. Objects are not magically created and garbage collected in the ether.
    The cost of creating a Date is nothing
    compared to the cost of a format() call. True, but not valid a valid statement pertaining to the issue which is
    "does always rolling dates suffer a performance hit?"
    Plus you lost clarity Maybe you loose track of your code if you don't make new Objects all the time,
    but I have never suffered from this.
    Why do you think Sun provided the setDate() method?
    and thread-safety.I have only had Thread issues when I didn't program them properly.
    Luckilly I always program the correctly ;) (Touch wood)
    The facts as I seem are thus:
    Rolling new dates on a 1.83 GHZ PC incurrs on average
    a 19% penalty. Here is the proof.
    Save this program and save it as DateTest.java
    If you don't want to waste the time here are the results of running it
    through the default 10 iterations.
    Running 10 iterations.
    Reuse of dates is 27% more efficient
    Reuse of dates is 17% more efficient
    Reuse of dates is 18% more efficient
    Reuse of dates is 20% more efficient
    Reuse of dates is 20% more efficient
    Reuse of dates is 17% more efficient
    Reuse of dates is 17% more efficient
    Reuse of dates is 20% more efficient
    Reuse of dates is 20% more efficient
    Reuse of dates is 18% more efficient
    Gaining "nothing " actually = 19% on average
    Low percent diff = 17 High percent diff = 27
    Run it 100 times and it should still be around 19%
    With the hi time being about 47% (Probably the result of garbage collecting)
    //////////////////////////////////// <PROOF> ///////////////////////////////////////
    import java.util.Date;
    public class DateTest
    DateTest()
    public int run()
    int percent = 0;
    int loopCount = 0;
    Date date = null;
    int z=0;
    long start1=0,end1=0,start2=0,end2=0,now=0;
    int time1 = 0,time2 = 0;
       now = System.currentTimeMillis();
       date = new Date(now);
       loopCount = 10000000;
       start1    = System.currentTimeMillis();
       for(z=0;z<loopCount;z++)
          now = System.currentTimeMillis();
          date.setTime(now);
       end1 = System.currentTimeMillis();
       start2    = System.currentTimeMillis();
       for(z=0;z<loopCount;z++)
          now   = System.currentTimeMillis();
          date  = new Date(now); // use 'now' so test loops are =.
       end2 = System.currentTimeMillis();
       time1 = (int)(end1 - start1);
       time2 = (int)(end2 - start2);
       percent = ((time2-time1)*100/time2);
       System.out.println("Reuse of dates is "+percent+"% more efficient");
       return percent;
    public static void main(String args[])
    int z=0;
    int lowP=100,hiP = 0;  // lowpercent/highpercent
    DateTest d = new DateTest();
    int loopCount = 0;
    long totals   = 0;
    int average   = 0;
    int values[];
    int retVal = 0;
       try // Yea olde Lazy person's command line handler :)
          loopCount = Integer.parseInt(args[0]);
       catch(Exception any)
          loopCount = 10;
       if(loopCount == 0)
          loopCount = 10;
       values = new int[loopCount];
       System.out.println("Running "+loopCount+" iterations.");
       for(z=0;z<loopCount;z++)  //
          retVal = d.run();
          if(lowP > retVal)
             lowP = retVal;
          if(hiP < retVal)
             hiP = retVal;
          values[z] = retVal;
       for(z=0;z<loopCount;z++)
          totals += (long)values[z];
       average = (int)(totals/loopCount);
       System.out.println(" Gaining \"nothing \" actually = "+average+"% on average");
       System.out.println("Low percent diff = "+lowP+" High percent diff = "+hiP);
    }////////////////////////////////// </PROOF> /////////////////////////////////////////
    Your "nothing" is in fact on average about a 19% performance hit. per call.
    These inefficiencies build up and java is infested with the,
    Was it not so the java would run much more efficiently than it now does.
    Ask yourself; why did Sun supply the setDate() method???
    (T)

  • Is it possible to convert from string to variant?

    Hi!
    I would like to convert a text string to variant. I'm doing this because I would like to merge a couple of signals and then save all the signals in a lvm-file. Could someone please explain how to convert from text to variant, is it possible?
    Thanks in advance!
    Regards,
    Mattias
    Attachments:
    Merge signals.JPG ‏27 KB

    What you are attempting to do is possible, but might not give you the results you expect.  All you need to do is convert your string to an array of U8s using the String to Byte Array conversion primitive.  In the file, you will get a single character per line of the file expressed as the ASCII code.  When you read it, convert to U8s, then use Byte Array to String to get your string back.
    You may also want to read up on LVM files.  There are several places to put strings that work a little better than this.
    This account is no longer active. Contact ShadesOfGray for current posts and information.

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

  • 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);

  • Parsing from string to int

    in my C# project I have an array type of String. the array gets numbers from type int.
    int numCell;
    string[] arr = new string[numCell];
    then i use it in a function like this:
    sum += int.Parse(arr[i]);
    and it works!
    but, when i dothe same thing in WPF it tells me:
    Input string was not in a correct format.
    what shouuld i do?

    Why did you mark your own question as answer? Please unmark it.
    >>if in C# it worked why wouldn't it work in wpf?
    As I have already mentioned, it is because of the actual value of arr[i]. It has nothing to do with Windows Forms or WPF but it is possible that your WPF application has put a different value in the array than your Windows Forms Application did. And if this
    specific value is not a valid number the parsing will always fail. So you should check the values that put into the array and probably use the int.TryParse method to do the parsing:
    int sum;
    if (!int.TryParse(arr[i], out sum))
    //the value of arr[i] was NOT a valid number...
    This will however not change the fact that for example the value "D1" cannot be converted to an int using the int.Parse or int.TryParse method.
    Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

  • Converting from String to float and vice versa

    I'm interested in people's thoughts on where common logic to convert between various field types should be stored in an application to minimise code duplication and maintenance.
    I have an application which consists of an object and a jPanel which displays and maintains this object. The object contains a number of private float fields which are accessed by getters and setters. The jPanel contains one jTextField for each of the fields within the object.
    Currently I have numerous lines of code in the jPanel to convert between the values needed by the getters and setters in the object (i.e. float) and the String value used by the jTextFields. This code handles cases where the String value may be blank or null.
    I've thought that one alternative to having all this conversion/validation code in the jPanel is to create a second set of getters and setters for each field which accept and return String values.
    What do people think about this? Is it advisable for only have one getter and setter for a variable? Should I put the conversion/validation logic for each field into a seperate common routine?
    Thanks,
    James.

    Hi James,
    You should go with whatever works best for you. By creating multiple getters and setter you save yourself from repeating the same code throughout your program.

  • Convert from String to Date for storing in SQL Server 2000

    Hi,
    I've accepted some values from a user using a form in HTML.Now using Servlets I transfer the value to my java code .
    I want to know how can I convert a DATE accepted from the user thats presently in "String" format to the "datetime" format for SQL Server2000.
    Please guide me with some steps and I shall be grateful.
    Thanks

    The java.text.SImpleDateFormat class is most probably of use.
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    String enteredDate = "25/12/2006";
    java.util.Date utilDate = sdf.parse(enteredDate);
    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());You can then use the java.sql.Date with the "setDate()" method of a prepared statement. This method would be database independant, as you are setting an actual date, not depending on a specific format on the database end.

  • Conversion from String to int..NumberFormatException??

    Hey all
    I am trying to read in a file that has nothing but numbers listed one per line. I am using the bufferedReader class and reading in by line. When I check to see if the one 'string' is the same as another, it says they are the same, when really they are different. I then thought to convert the numbers to integers after reading them in, but it gives me a number format exception. My process is simple:
    1) line = in.readLine();
    2) int variable = Integer.valueOf(line).intValue();
    This gives me the damn exception. The numbers are three digits, e.g. 333, etc. Does anybody know how I can avert this problem or achieve the result I am looking for another way? All I want is to know what numbers are listed in their, without going through by hand checking. Thanks

    hi...try this..
    1.Use filereader instead of bufferedreader..OKAY
    2. OR USE...
    String str = br.readLine();
    use... int sanjeev = Integer.parseInt(str);
    3 OR...and helloooo one thing more...how u r checking that these 2 strings r same..
    get CLEAR IDEA about equals method and "=="..

Maybe you are looking for