Convert string to integer

package onjava;
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;
import java.lang.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CalcClient extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"");
out.println("\"http://www.w3.org/TR/html4/loose.dtd\">");
out.println("<html>");
out.println("<head>");
out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">");
out.println("<title>Substraction using SOAP</title>");
out.println("</head>");
    URL url = new URL ("http://localhost/soap/servlet/rpcrouter");
Integer p1=request.getParameter("param1");
Integer p2=request.getParameter("param2");
In the above statement i have to convert the string to integer because that has to be passed in my program as an argument to a function so please let me know how to do that
    // Build the call.
    Call call = new Call();
    call.setTargetObjectURI("urn:onjavaserver");
    call.setMethodName("subtract");
    call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
    Vector params = new Vector();
    params.addElement(new Parameter("p1", Integer.class, p1, null));
    params.addElement(new Parameter("p2", Integer.class, p2, null));
    call.setParams (params);
    // make the call: note that the action URI is empty because the
    // XML-SOAP rpc router does not need this. This may change in the
    // future.
    Response resp = call.invoke(url, "" );
    // Check the response.
    if ( resp.generatedFault() ) {
      Fault fault = resp.getFault ();
     out.println("The call failed: ");
     out.println("Fault Code   = " + fault.getFaultCode());
     out.println("Fault String = " + fault.getFaultString());
    else {
      Parameter result = resp.getReturnValue();
      out.println(result.getValue());
out.println("</body>");
out.println("</html>");

Two possibilities: Try either java.lang.Integer.valueOf() or java.text.NumberFormat and its parse method.
Either one will do what you want. I think Integer will be the simpler of the two.
The code you have is obviously not correct, because getParameter returns a String:
Integer p1=request.getParameter("param1");Do it like this:
Integer p1=Integer.valueOf(request.getParameter("param1"));%

Similar Messages

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

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

  • Beginner ?: Converting String to Integer

    Hello!  I'm having some trouble converting a string to an integer.  Here is my code:
    var str:String = e.currentTarget.name as String; // Getting values like "song1", "song2"
    str = str.replace("song", ""); // Changes it from "song1" or "song2" to "1" or "2"
    var num:int = str as int; // SHOULD be converting the "1" to 1 and "2" to 2
    trace("num:" + num + ", str:" + str);
    The trace is always outputting:
    num:0, str:1
    num:0, str:2
    etc..
    The str value is there, but when it gets put into num then it zeros out.  What am I doing wrong?
    Thanks in advance!

    Try using:  var num:int = int(str);

  • Typecasting string to integer. need help

    Hi,
    I have the following statement which returns a String but i need to convert to an integer .
    properties.getProperty("MAXWIDTH");
    Can i do it this way,
    int width = (Integer) properties.getProperty("MAXWIDTH");
    But it gives me error stating that it cannot convert string to integer.
    Please help
    Purnima

    That's because the value returned from the
    getProperty() method is a String. You can convert it
    to an int, like this:int width =
    Integer.parseInt(properties.getProperty("MAXWIDTH"));[
    /code]oh so simple thanks
    Purnima

  • 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

  • Convert text box string into integer

    i have an html file in which i m using a text box , for entering amount i m using that text box entry at next jsp. i want to convert amount string into integer for further processing. At next jsp i m using:-
    String amount= request.getParameter("bal");
    int ammount1= Integer.parseInt(ammount);
    and in sql query i m using amount1 as:-
    ResultSet rs1 = st.executeQuery("update saving set balance = balance - amount1 where saving.account_no = '" + acc +"'");
    my problem is i m getting following error:-
    server encountered an internal error and
    exception:- numberformat exception
    please help me as soon as possible

    int ammount1= Integer.parseInt(ammount).toString();
    good to put try block too..
    try
    int ammount1 = Integer.parseInt(ammount).toString();
    catch(NumberFormatException e)
    ...}

  • Converting String to unicode encoded string

    Hi,
    I would like to convert non-ascii characters in a String or the whole string to unicode encoded character.
    For example:
    If i have some japanese character, I would like it to be converted to /uxxxx
    How can i do this? I don't want the exact character, as I am able to get that using getBytes("encoding format"). All i want is code point representation of the non ascii unicode characters.
    Any help to do this will be appreciated.
    Thanks in advance.

    I tried to do what that but I am not sure whether that is right or not.
    String inputStr = "some non ascii string";
    char[] charArray = inputStr.toCharArray();
    int code;
    StringBuffer sb = new StringBuffer();
    for(int i = 0; i < charArray.length; i++)
    code = (int) charArray;
    String hexString = Integer.toHexString( code );
    sb.append(hexString);
    System.out.println("Code point is "+sb.toString());
    My above code does not work as expected. Could you please tell me where i am goofing?
    Thanks!

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

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

  • Append String to Integer

    Hi Guys,
    I am trying to append a String to Integer like this;
    String areacode = 020;
    Integer phone_no = 21354214;
    Integer full = areacode && phone_no;My problem is how to join the two datatypes to a single Integer value. Do anyone know how to go about this?
    B

    sabre150 wrote:
    Skotty wrote:
    Without debating the logic of doing such a thing...
    Concatenate them as Strings, then convert that String back to an Integer.Your are on the top floor of the Eiffel Tower and a man is trying to climb over the safety netting but having trouble climbing the netting. You ask him why he is doing this and he says he has to get down to the ground as soon as possible but he has an irrational fear of lifts. Do you help him climb the safety netting or do you advise him that this is not a good idea and try to stop him?I get him to use my camera to take my picture.

  • Easier Way to convert Hex to Integer

    This problem is mainly to do with a hex string to integer conversion.  The device, connected via serial connection outputs hex in the format 0A00, when looking at it in hex.  The first two digits are the data, the last two are attached to seperate data points.  what I'm trying to do is to raster the last 2 digits off so that 2A00 becomes 2A and then convert the 2A into integer format (42).  I have come up with a method to do this, but it is very messy and occasionally results in data loss.  I have attached my vi (8.2).  The large integer being subtracted is a constant that continues to come up for reasons I am not aware of.
    another issue which I am coding through is the fact that sometimes a byte slips by, making 2A00 become 00BB or something of that format.  Is there a way to scan the string, determine whether the first two digits or the last two digits are the valid ones and then seperate the valid string?  In this code, it would be necessary to allow for the value 0000 to read 0.
    If there is confusion, here is some examples of incoming data and desired output
    0100 - 1
    0A00 - 10
    0005 -5
    000B - 11
    etc.
    Solved!
    Go to Solution.
    Attachments:
    geiger read.vi ‏28 KB

    Since you are reading 2 bytes, it looks like you should be dealing with a 16 bit number. Typecast to U16 rather than I32 like you are doing now. And all of that string manipulation make it look like you are getting a string of ASCII formatted characters like "0" "A" "1" "B" rather than a 2 byte string of ASCII characters 0A and 1B. Then you can split the U16 number and take the higher order byte.
    I can't explain why you would be having a byte slip by unless it has something to do with all that string manipulation you are trying to do.  But if it still happens, and you know one byte for the other is always zero.  Just take the high order byte and add it to the low order byte.  Since one is zero, it will have no effect on the other byte.
    Message Edited by Ravens Fan on 07-07-2009 01:54 PM
    Attachments:
    geiger%20read[1]_BD.png ‏3 KB

  • Not able to convert string attribute to number and date please help me out

    not able to convert string attribute to number and date attribute. While using string to date conversion it shows result as failure.As I am reading from a text file. please help me out

    Hi,
    You need to provide an example value that's failing and the date formats in the reference data you're using. It's more than likely you don't have the correct format in your ref data.
    regards,
    Nick

  • Convert String to Date and Format the Date Expression in SSRS

    Hi,
    I have a parameter used to select a month and year  string that looks like:    jun-2013
    I can convert it to a date, but what I want to do is,  when a user selects a particular month-year  (let's say "jun-2013")
    I  populate one text box with the date the user selected , and (the challenge Im having is)  I want to populate a text box next to the first text box with the month-year  2 months ahead.    So if the user selects 
    jun-2013   textbox A will show  jun-2013 
    and textbox B will show  aug-2013..
    I have tried:
    =Format(Format(CDate(Parameters!month.Value  ),  
    "MM-YYYY"  )+ 2  )   -- But this gives an error
    This returns the month in number format   like "8"    for august...
    =Format(Format(CDate(Parameters!month.Value  ), 
    "MM"  )+ 2  )
    What is the proper syntax to give me the result    in this format =  "aug-2013"  ???
    Thanks in advance.
    MC
    M Collier

    You can convert a string that represents a date to a date object using the util.scand JavaScript method, and then format a date object to a string representation using the util.printd method. For more information, see:
    http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.1254.html
    http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.1251.html
    In your case, the code would be something like:
    var sDate = "2013-01-10";
    // Convert string to date
    var oDate = util.scand("yyyy-mm-dd", sDate);
    // Convert date to new string
    var sDate2 = util.printd("mm/dd/yyyy", oDate);
    // Set a field value
    getField("date2").value = sDate2;
    The exact code you'd use depends on where you place the script and where you're getting the original date string, but this should get you started.

  • Convert String variable value  to an Object referece type

    Hi all,
    I want to know that if there any possible way to convert String variable value to a Object reference type in java. I'll explain by example if this is not clear.
    Let's think that there is a string variable name like,
    String name="HelloWorld";
    and there is a class name same to the variable value.
    class HelloWorld
    I am passing this string variable value to a method which is going to make a object of helloworld;
    new convertobj().convert("HelloWorld");
    class convertobj{
    public void convert(String name){
    // in hert it is going to create the object of HelloWorld;
    // HelloWorld hello=new HelloWorld(); just like this.
    now i want to do this from the name variable value.( name na=new name()) like wise.
    please let me know if there any possible way to do that.
    I am just passing the name of class by string variable then i wanted to make a instance of the class which come through the variable value.
    thanx.

    Either cast the object to a HelloWorld or use the reflection API (Google it) - with the reflection API you can discover what methods are available.
    Note: if you are planning to pass in various string arguments and instantiate a class which you expect to have a certain method... you should define an interface and have all of your classes that you will call in this way implement the interface (that way you're sure the class has a method of that name). You can then just cast the object to the interface type and call the method.
    John

Maybe you are looking for