Re: Converting a string to an integer
Andrew Thompson wrote: a bunch of stuff that I have committed to memory
Hi Andrew,
I finally figured out what I did wrong.
When I read the java docs, I didn't see the connection
http://download.java.net/jdk7/docs/api/java/lang/Integer.html#decode(java.lang.String)
The sequence of characters following an optional sign and/or radix
specifier ("0x", "0X", "#", or leading zero) is parsed as by the
Integer.parseInt method with the indicated radix (10, 16, or 8). This
sequence of characters must represent a positive value or a
NumberFormatException will be thrown. The result is negated if first
character of the specified String is the minus sign. No whitespace
characters are permitted in the String.
"leading zero" is the way that octal is represented. I was assuming
that it was a O (capital letter O) rather than a 0 zero.
If I had been reading more closely, I would have seen the paragraph above it
Decodes a String into an Integer. Accepts decimal, hexadecimal, and
octal numbers given by the following grammar:
DecodableString:
Signopt DecimalNumeral
Signopt 0x HexDigits
Signopt 0X HexDigits
Signopt # HexDigits
Signopt 0 OctalDigits
Sign:
-
+
which should have given me the hint that I needed.
Anyway... thanks for the help. My conversion program
<SSCCE>
public class WillThisWork {
public static void main(String [] args) {
String s = "023";
String y = s.trim();
Integer x = java.lang.Integer.decode(y);
System.out.println("s as a string is " + s);
System.out.println("y as a string is " + y);
if (s.equals(y))
{
System.out.println("They are the same");
}
else
{
System.out.println("They are different");
}
System.out.println("Now see what x is " + x);
}
}
</SSCCE>
Is now working the way I expected it to.
s as a string is 023
y as a string is 023
They are the same
Now see what x is 19
I know that this is probably a silly question, but if I import
java.lang.Integer.* why do I still have to fully qualify decode()? Is
it because it's a static method and MUST be fully qualified?
Note: I'm not far enough in the Java Tutorial to answer this question
so that's the only reason I'm asking you...