Archived

This topic is now archived and is closed to further replies.

jhwc1138

Java String To Int Conversion Problem!!

Recommended Posts

Hi All!! When I''m doing homework it seems that type conversions hang me up more than anything! Why can''t I just assign a String to an Int Dammit! Anyway... I''m reading in a .txt file of numbers seperated by \n charecters. My code looks like this:
  
String Temp;
Int IntTemp;

for (int i = 0; i < numLines; i++
{
Temp = inputFile.readLine();
IntTemp = java.lang.Integer.parseInt(Temp)
}
  
This works fine execpt when I call parseInt I only go through the loop once!! If I comment out the parseInt and System.out.println(Temp); It goes through numLines times like it should! What gives? Is there a better way to convert these types! Thanks!

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Here''s how I do it:


  
Integer myInt;
// Read an integer from a file

if ((inputLine = file.readLine()) != null)
{
myInt = new Integer(inputLine));
}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
I don''t see why not.

I would check the line you''ve read for null though.
and stop inputting when you reach that (maybe use it for error checking?).

Share this post


Link to post
Share on other sites
You can''t assign an Integer object to a variable of type ''int'' as far as I know. If you have some String x, then :

int y = Integer.parseInt(x);

will convert your String to an int. Or to use your previous example :

a = Integer.parseInt(inputLine);

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Argus is absolutely right, you cannot assign an Integer instance to an int directly. (I think it is to make the vm more effecient by keeping primatives totally distinct). His code is absolutely correct, but doesn''t account for any leading 0''s that may have been entered. You can fix the radix to base 10 as below.

a = Integer.parseInt(inputLine, 10);

Or if you want it to handle the different base representations(0x, 0, etc) I think the decode method is preferred (it is explicitly mentioned in Nutshell over the parseInt method). this returns an Integer instance but can be converted to an int by the intValue() method.

a[i] = Integer.decode(inputLine).intValue();

Share this post


Link to post
Share on other sites