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
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++;
}