struts-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Scott Van Wart <sc...@indosoft.com>
Subject Re: Converting an object to integer
Date Fri, 21 Jul 2006 19:27:28 GMT
temp temp wrote:
> The object which I want to convert into Integer is a number and can be converted to int,
its not a string or a boolean .
> I get this object either from  request attribute , or request parameter or a DAO.
>   If  I  get this  ob ject  from request parameter I  cannot cast it to integer  because
I get compilation error stating  that  cannot cast a String to integer in this case do I have
to  create a new Integer every time ?
>   Thanks & Regards
>   
Technically the code I wrote below will work for String objects as well. 
You have to create a new integer every time, because it first needs to 
be parsed. It might be a number, but it's a number stored in a String. 
You have to express this to the language:

Integer someInt = new Integer( request.getParameter( "param" ) );

You also have to wrap it in try { ... } catch ( NumberFormatException e 
) { ... } for those "just in case" situations.

If it's an attribute of the request, you need to first cast it to a 
String, if that's the way it was stored:

Integer someInt = new Integer( (String)request.getAttribute( "attr" ) );

- Scott
>   
>   
> Scott Van Wart <scott@indosoft.com> wrote:  temp temp wrote:
>   
>> What is the best way to convert an object to an Integer  .If casting dosen't work?
>>   
>>     
>
> Object probablyAnInteger = ....;
>
> Integer someInt;
> if ( probablyAnInteger == null || probablyAnInteger.equals( "" ) )
> {
>   someInt = null;
> }
> else
> {
>   try
>   {
>     someInt = new Integer( probablyAnInteger.toString() );
>   }
>   catch ( NumberFormatException e )
>   {
>      // definitely not an integer
>      someInt = null;
>   }
> }
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
> For additional commands, e-mail: user-help@struts.apache.org
>
>
>
>  		
> ---------------------------------
> How low will we go? Check out Yahoo! Messenger’s low  PC-to-Phone call rates.
>   


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Mime
View raw message