Java String To Int Conversion Problem!!

Started by
4 comments, last by jhwc1138 21 years, 6 months ago
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!
Advertisement
Here''s how I do it:


  Integer myInt;// Read an integer from a fileif ((inputLine = file.readLine()) != null){  myInt = new Integer(inputLine));}    
Ok... but can I then do this?

  int a[] = new int[numLines]for(int i = 0; i < numLines; i++){Integer myInt;inputLine = file.readLine();myInt = new Integer(inputLine));a[i] = myInt;}  [\source]  
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?).
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);

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 = Integer.decode(inputLine).intValue(); </i>

This topic is closed to new replies.

Advertisement