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

Time:11-29

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 52x2 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]);
        }
    }
}

CodePudding user response:

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

CodePudding user response:

As your data also adheres to the .properties format, you can use the Properties class.

Path file = Paths.get("...");
Properties properties = new Properties(52); // Initial capacity.
properties.load(Files.newBufferedReader(path, StandardCharsets.ISO_8859_1));

properties.list(System.out);
String name = properties.get("AR", "Arabia?");

Here I used an overloaded get where one can provide a default ("Arabia?") in case of failure.

CodePudding user response:

Use the predefined split() String function:

// A string variable.
String myString = "Hello:World";
// split the string by the colon.
String[] myStringArray = myString.split(":");
// print the first element of the array.
System.out.println(myStringArray[0]);
// print the second element of the array.
System.out.println(myStringArray[1]);
  •  Tags:  
  • java
  • Related