Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to convert string to short  RSS feed

 
Sanjul Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how can i convert string to short in java.

thanks in advance,
sanjul
 
Rene Larsen
Ranch Hand
Posts: 1179
Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
short s = Short.parseShort(String);

Rene
 
Sanjul Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for your reply, but its not working. this is what i have done:



I need to print the value of s.


Regards,
Sanjul
 
Giovanni De Stefano
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sanjul,
please make up your mind with what you are trying to do.

You asked in your first post how to convert a string into a short, and Rene told you how to do it properly.
Then, in your second post you say that you need the value of 's' BUT you are parsing a string into a Short WITHOUT noticing that the string itself CANNOT be recognized as a number because it is 'ltest' !!!

Here is a WORKING example:


Try with g = "24" and, for example, g = "24a".

Giovanni
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sanjul Jain:
thanks for your reply, but its not working. this is what i have done:



I need to print the value of s.


Regards,
Sanjul

You should post what happens when you run this example. I would guess that you are seeing the output when from the catch clause because an exception is thrown. The problem is that the String "1test" cannot be parsed to a short because it has non-numerical characters in it.

For future reference, it would be more helpful to do something like

in the catch clause. This will give you some helpful information when you an exception occurs unexpectedly in your program.

HTH

Layne
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!