Converting a string to an integer

J

jt

<Question>

Why does the NumberFormatException get thrown when the String argument
is not empty?
</Question>

<Background>

I was reading the Sun Tutorial and happened across the section on integers:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html

I saw the bit on octal and hex representations and thought that I might
be able to take a string containing..oh say "O23" and use the
Integer.parseInt method to convert it to an integer. After all, the
tutorial does say

The prefix 0 indicates octal, whereas 0x indicates hexadecimal.

int decVal = 26; // The number 26, in decimal
int octVal = 032; // The number 26, in octal
int hexVal = 0x1a; // The number 26, in hexadecimal

Here's my code:

package just_playing_around;

public class WillThisWork {
public static void main(String [] args) {
String s = "O23";
int x = Integer.parseInt(s.trim());
System.out.println("s as a string is " + s);
System.out.println("s as an integer is " + x);
}
}


And here's the error I get when I run it

Exception in thread "main" java.lang.NumberFormatException: For input
string: "O23"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at just_playing_around.WillThisWork.main(WillThisWork.java:6)
</Background>

<Research>
1) I did a google search on cljp and found the following post

http://groups.google.ca/group/comp....Unknown+Source)&rnum=7&hl=en#d7610d111ecc7ceb

If you will notice Patricia's post

I think this is the critical data. It claims that there was an
Integer.parseInt call on line 72 with the empty string as input.

Does that make sense?

Patricia

2) I tried to eliminate the probable causes of the "empty string" in
the following sequence

2a) I removed the parseInt and print for x from my code.

package just_playing_around;

public class WillThisWork {
public static void main(String [] args) {
String s = "O23";
// int x = Integer.parseInt(s.trim());
System.out.println("s as a string is " + s);
// System.out.println("s as an integer is " + x);
}
}

s as a string is O23

2b) In the same program, I did the trim and assigned the value to a new
string so that I could see what the result of the string was without
disturbing the original. I also added a comparison to see if indeed
both strings were the same.

package just_playing_around;

public class WillThisWork {
public static void main(String [] args) {
String s = "O23";
String y = s.trim();
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");
}
}
}

s as a string is O23
y as a string is O23
They are the same
<Research>
<Theory>
Either the runtime error I am getting is misleading (see Research.1> or
the runtime error is pointing me to something else, something more
insidious.
</Theory>
<Followup>
Where am I going wrong? Did I mis-read something somewhere or is what I
am trying to do just not do-able using the tools I have available to me
right now?
</Followup>

Thanks for your help
 
J

jt

Stefan said:
This starts with the letter »O«.


This starts with the digit »0«.
Yes I know that. My code shows:

String s = "O23";

which is the letter O... O23 is the octal number. 023 (number 0) would
simply be 23.
 
J

jt

Stefan said:
Ahh... now I understand. So why did the program even compile in the
first place? I'm using Eclipse 3.2 and jdk 1.6
Is this one of those cases where Java doesn't pay attention to what you
are trying to do until you try to run the code?
 
A

Andrew Thompson

Stefan Ram wrote: ....
....
I can't find the decode method in the API for jdk1.6 Is a new feature
added to jdk7?

No, AFAIU it was introduced in 1.0.

Here it is in the *1.5* docs ..
<http://java.sun.com/j2se/1.5.0/docs/api/java/lang/
Integer.html#decode(java.lang.String)>
I would have put a link to an even earlier
version of the JavaDocs, but I don't know
of any URL's for the earlier JDocs.

Andrew T.
 
S

starf

Ahh... now I understand.  So why did the program even compile in the
first place?  I'm using Eclipse 3.2 and jdk 1.6
Is this one of those cases where Java doesn't pay attention to what you
are trying to do until you try to run the code?

just like 1/0 can not be realized. this error should be caught in the
runtime.
 
A

Andrew Thompson

....
Shoot... it's an Integer not an int. Sorry Andrew.

No need for apologies, but could I ask that
you refrain from 'full-quoting' in future?

Note that in my reply, I trimmed most of my
earlier text (which was no longer relevant)
as well as my 'signature' at the bottom of
my first post (if people are that interested
in 'who said what', they can read it in the
lines like 'Bob wrote:'/'Stefan wrote:'..).

This helps reduce the bandwidth that others
reading the group (who may not even be following
this thread) have to get in order to read
the group. It is a courtesy to spare them
the unnecessary bytes.

(And, preemptively, an assurance of 'will do'
is far preferable to any form of apology.)

Andrew T.
 
J

jt

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

Jeff Higgins

jt wrote:

import static java.lang.Integer.*;
public class WillThisWork {
public static void main(String [] args) {
String s = "023";
String y = s.trim();
Integer x = java.lang.Integer.decode(y);

Integer x = decode(y);
 
A

Andrew Thompson

Andrew Thompson wrote: a bunch of stuff that I have committed to memory

Wow! I may ask you to repeat it back to me at
some later date, because to be honest, I would
have to reread the thread before I could recall
what I said!
( I Hope I did not use any swear words ;)

...
...No whitespace
characters are permitted in the String.

Uh-huh. I saw something in your code further
down that made me wonder if you had correctly
interpreted what a 'white space character' is.. *
"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.

Damn, I wish I was using a font that showed
a difference, those O/0 look identical on this
box/config.
<SSCCE>
public class WillThisWork {
public static void main(String [] args) {
String s = "023";

* the '0' will not be considered a 'white space char.',
the things that would be considered white space might
be summed up as..

<sscce>
import javax.swing.*;

class ShowWhiteSpace {

public static void main(String[] args) {
// sure I've forgotten some..
String untrimmed = "\t 01234Hi! \n\n ";
String trimmed = untrimmed.trim();
JTextArea ta = new JTextArea(
"untrimmed: \t'" + untrimmed + "'\n" +
"trimmed: \t'" + trimmed + "'"
);
JOptionPane.showMessageDialog(null, ta);
}
}
I know that this is probably a silly question, but if I import
java.lang.Integer.*

Assuming you meant..
import java.lang.Integer.*;
...that is a compilable, but invalid, statement.

The ones that would have the right effect are either ..
import java.lang.Integer;
...or..
import java.lang.*;

The '*' character can import into the namespace,
all classes within a particular package, as done
in the second statement.

The first statement is preferable* though, as
it is an explicit import for the one required
class, and is better documented as a result.

Importing the class (using either form) will
automatically make *all* it's methods available.

* I usually use package imports in SSCCE's,
for the sake of brevity, but it should not
generally be done in 'real' or production
code.

HTH

Andrew T.
 
J

jt

Andrew said:
Wow! I may ask you to repeat it back to me at
some later date, because to be honest, I would
have to reread the thread before I could recall
what I said!
( I Hope I did not use any swear words ;)
No, AFAIU it was introduced in 1.0.

Here it is in the *1.5* docs ..
<http://java.sun.com/j2se/1.5.0/docs/api/java/lang/
Integer.html#decode(java.lang.String)>
I would have put a link to an even earlier
version of the JavaDocs, but I don't know
of any URL's for the earlier JDocs.

Andrew T.
 
O

Oliver Wong

jt said:
Ahh... now I understand. So why did the program even compile in the
first place? I'm using Eclipse 3.2 and jdk 1.6
Is this one of those cases where Java doesn't pay attention to what you
are trying to do until you try to run the code?

It's more like a case of Java not actually executing methods until you
actually run them. The method java.lang.Integer.parseInt(java.lang.String)
has a certain behaviour. Specifically, if you pass it the string "023", it
will return 23, and if you pass the string "O23", it will throw a
NumberFormatException. But the method does these things when the method
actually runs, not when you compile it.

This is similar to the concept that System.out.println("Hello world!")
will print out "Hello world!" to your console when that method actually
runs, and not when you compile the program.

- Oliver
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,739
Latest member
Clint8040

Latest Threads

Top