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

Trying to read the contents of a file into an array, but the contents are separated by a colon

Inside my file is the two-letter abbreviation of each state followed by the full name of the state, and each state abbreviation and name is separated by a colon.

Like this:

al:Alabama

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

ak:Alaska

I need to read this into an array of 52×2 and I am not sure how to do that. The code I have now just reads each line from the file into the array without separating the abbreviation and name.

String[][] states = new String[52][2];

while (input2.hasNext()) {
    for (int row = 0; row < states.length; row++) {
        for (int column = 0; column < states[row].length; column++) {
            states[row][column] = input2.next();
            System.out.printf("%s%n", states[row][column]);
        }
    }
}

>Solution :

You can try below code(Comments inline):

String[][] states = new String[52][2];

int row = 0;

while (input2.hasNext()) {
    
    // Read whole line from the file
    String line = input2.nextLine();
    
    // Split string into tokens with : character.
    // It means, Line: al:Alabama is converted to
    // ["al", "Alabama"] in tokens
    String tokens[] = line.split(":");
    
    // Store first token in first column and similarly for second.
    states[row][0] = tokens[0];
    states[row][1] = tokens[1];
    
    row++;
}
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