The JSP Files (part 3): Black Light And White Rabbits - You Say Seven, I Say 7
(Page 6 of 7 )
And finally, in case you've ever wanted to convert strings to numbers, the following example should tell you everything you need to know.
<%
// converting a string to a number
// define variables
String someString = "97";
int aRandomNumber = 3;
// at this stage, someString is still treated as a string
out.println(someString + " plus " + aRandomNumber + " equals " +
(someString+aRandomNumber) + "<p>");
// now convert someString to a number
int someNumber = Integer.parseInt(someString);
// at this stage, someString has been converted to a number, stored in
someNumber
out.println(someNumber + " plus " + aRandomNumber + " equals " +
(someNumber+aRandomNumber));
%>
And here's the output.
97 plus 3 equals 973 97 plus 3 equals 100 [output]
If you'd prefer to do things the other way around, the next example bears careful consideration.
<%
// define variables
int someNumber = 97;
int aRandomNumber = 3;
// at this stage, someNumber is still treated as a number
out.println(someNumber + " plus " + aRandomNumber + " equals " +
(someNumber+aRandomNumber) + "<p>");
// now convert someNumber to a string
String someString = Integer.toString(someNumber);
// at this stage, someNumber has been converted to a string, stored in
someString
out.println(someString + " plus " + aRandomNumber + " equals " +
(someString+aRandomNumber));
%>
And here's the output.
97 plus 3 equals 100
97 plus 3 equals 973
The upshot? parseInt() and toString() are your best
friends when converting between string and numeric data types in JSP.
Next: A Positive Response >>
More Java Articles
More By Vikram Vaswani and Harish Kamath, (c) Melonfire