Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert string to int in array

Im trying to read a line of file that has words and numbers in it and save it into a array

The file reads:

Barrett Edan 70 45 59

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Part of the code that has a problem:

** let it be known that field was declared as a string array earlier in the code**
String [] fields = new String[100];
int [] numfields = new int[100];

while (reader.hasNext()) {     //while reader reads a line
  line = reader.nextLine();  //line reads reach line of file
  fields = line.split("\t");  //splits line by tab space and saves it into fields
  
  last[count] = fields[0];   // saves first word to first element of array
  first[count] = fields[1]; //saves second word to second element
  numfields[0] = fields[2]; /* THE PROBLEM: now i expected the 3rd word (70) of fields to be able to save into numfields array , but thats when i get cannot be converted to int error
  numfields[1] = fields[3];
  numfields[2] = fields[4];    */

>Solution :

You have to explicitly convert from String to int. Java will not do this for you automatically.

numfields[0] = Integer.parseInt(fields[2]);
// and so on...

Presumably this line of data pertains to a single "thing" in whatever problem you’re working on. Parallel arrays area bad habit to get into. Rather you want one array/list/whatever composed of objects which hold all of the data pertaining to a single "thing."

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading